Simple Apache redirects

If you look around the web, you’ll see endless tutorials on how to configure Apache to do redirects using mod_rewrite. Undoubtedly mod_rewrite is a powerful way to control access and redirects on your Apache server, and it is enabled on many web hosts, but before you dive into the complexity and regular expressions of mod_rewrite, why don’t you give mod_alias a chance – you don’t have the power that you’ve got with mod_rewrite, but it is a lot simpler. Shall we take a look? Let’s take the example of ensuring that you have a canonical domain which uses the ‘www.’ at the beginning. (A canonical domain is a techie way of saying that rather than having the same content available at http://www.example.com/some-page.html and http://example.com/some-page.html, the site owner picks one preferred form of URL and redirects all content from other URLs to their preferred form of URL – it’s good for Search Engine Optimisation.) With mod_alias you can add the following directive to your .htaccess file, or Apache config:

Redirect permanent / http://www.example.com/

Let’s just step through what the code snippet above does; and don’t worry, it’s as simple as it looks:

  1. Redirect – This is a redirect rule
  2. permanent – The redirection information should be considered permanent, if the program (i.e. web browser or Google or whatever) can automatically change the bookmark they had for the previous page, then they should
  3. / – The target, i.e. what should be redirected, in this case it’s everything from the root of the website upwards
  4. http://www.example.com/ – The destination, i.e. where the redirection should end up, in this case it’s http://www.example.com

The rule above rule will make the following redirections (and more):

  • http://example.com/ -> http://www.example.com/
  • http://example.com/whatever -> http://www.example.com/whatever
  • …etc

Sadly if you want to redirect in the other direction, which Sam Clark believes is correct (we disagree on this point), then you will need the added complexity of mod_rewrite. However, for other simple redirections where you’ve moved content without your site, so if you’ve moved http://www.example.com/election-procedures/ to http://www.example.com/archive/2007/election-procedures, then the following directive is your friend:

Redirect permanent /election-procedures/ http://www.example.com/archive/2007/election-procedures/

Hopefully this is useful for you. I use mod_alias in projects a lot more than I use mod_rewrite, and I find my .htaccess code clearer and easier to understand because of it.

Join the Conversation

2 Comments

  1. Interesting post, I tend to use mod_rewrite as a matter of course but now you mention mod_alias, there’s no good reason that I should do it that way. Thanks for the article!

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.