WordPress URL Shortening Hack

My last post, Publishers Shorten Yourself, got me thinking about easy, low-tech ways to provide a short url for WordPress blogs.

Turns out, just 1 line of code is needed in the .htaccess file.
RewriteRule ^(d+)$ http://[YOUR-BLOG-URL]/?p=$1

Add it in just after RewriteBase so your .htaccess looks something like this:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^(d+)$ http://[YOUR-BLOG-URL]/?p=$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

To use this short URL in your templates do one of the following:

If you want to use the same domain your blog is on, use this:

<a href="<?php echo get_option('home'); ?>/<?php the_ID(); ?>"><?php echo get_option('home'); ?>/<?php the_ID(); ?></a>

If you have a different, perhaps shorter domain, use this:

<a href="[SHORT-DOMAIN]/<?php the_ID(); ?>">[SHORT-DOMAIN]/<?php the_ID(); ?></a>

Note: You will have to add an additional redirect to the .htaccess file of SHORT-DOMAIN, but that’s not problem, because it’s very similar to the WordPress redirect we started with.

And like that you’ve got a short url, for every post in your WordPress blog. No more worries about whether or not a specific URL shortener will be stealing your referrers or even be around tomorrow.

3 thoughts on “WordPress URL Shortening Hack

Share Your Thought