.htaccess files

If you've never delved into murky world of URL redirection using .htaccess files, you can happily close this tab and move on with your day.

However, if, like me, you've had the need to set up redirection of a domain, and have never learnt the Apache programming language (and let's face it, this isn't high on most people's bucket list…), then I've found a great resource that will help you out.

Firstly, let's define what an .htaccess file is:

The .htaccess file is usually a set of rules that you want your Apache web server to follow when displaying your site to web visitors.

For example, let's say that you delete a blog post, but want to redirect anyone who visits that link to a new post you've written.

If your website was run on an Apache web server (and this is pretty common for most WordPress sites) you'd probably use a rewrite rule in the .htaccess to redirect those visitors.

Scott Phillips = Superhero

Now there's a guy called Scott Phillips who's a clever Mo-Fo based in LA, and he's put together a simple copy-and-paste guide to .htaccess rules.

What that means is that 90% of the things you'll want to achieve in an .htaccess file can be found in his Gist (here on GitHub).

And you don't need to learn all the nerdiness to use them

For example, if you move your blog from blog.CatStevens.com to CatStevens.com/blog then he provides the exact ‘code' you need to copy and paste into your .htaccess file.

RewriteCond %{REQUEST_URI}/ blog
RewriteRule ^(.*) http://www.catstevens.com/%{REQUEST_URI} [R=302,NC]
RewriteRule ^(.*) http://www.catstevens.com/blog/%{REQUEST_URI} [R=302,NC]

Pretty cool, isn't it?

The biggest mistake I nearly made…

Anyway, no post on rewrite rules would be complete without a warning (and I almost learnt this the hard way!).

Getting something wrong in this file CAN FUCK YOUR SITE UP, so always make sure you keep copies of original files.

I use the ‘comment' feature to remove any lines and check the result before deleting them. For example, let's say I want to delete the first redirect rule in this file:

RewriteCond %{REQUEST_URI}/ blog

# I WANT TO DELETE THE LINE BELOW
RewriteRule ^(.*) http://www.somewhere.com/%{REQUEST_URI} [R=302,NC]
RewriteRule ^(.*) http://www.somewhere.com/blog/%{REQUEST_URI} [R=302,NC]

So instead of deleting it, and the realising that I had made a huge mistake, I simple add a ‘#' before the line and it's ignored. Like this:

RewriteCond %{REQUEST_URI}/ blog

# I ADD A # AND THE LINE IS IGNORED
# RewriteRule ^(.*) http://www.somewhere.com/%{REQUEST_URI} [R=302,NC]
RewriteRule ^(.*) http://www.somewhere.com/blog/%{REQUEST_URI} [R=302,NC]

Anyone who's ever edited a CSS file will know the same is achieved with ‘/**

Oh and be careful if you use a caching plugin, as this can make you think your changes have not taken effect.

Scott's Cheatsheet

So here is Scott's cheatsheet. You can find the original over on GitHub.

Want to learn more? This article is a good place to start.