Apache redirect rules for moving your site to a new domain.

So you are moving your website or blog to a new domain / url, but what happens to all that people and search engines trying to reach the OLD domain that you are leaving ?

Well, as you maybe noticed, I have moved my blog to a subdomain (yes, now this blog is at http://blog.massanti.com) and i was somehow worried about how to deal with all that people and search engines still going to the OLD url (http://massanti.com), so obviously, one thing came to my mind: “Apache redirects”.

This took me a whole 5 minutes to write, so I’m writing it here just for anybody interested.

Basically, the goal was to redirect anybody going to massanti.com/someblog/post/here to blog.massanti.com/someblog/post/here AS LONG as the file doesn’t exists on massanti.com: i.e: i don’t want massanti.com/somedir/somerealpage.html being redirected to blog.massanti.com/somedir/somerealpage.html.

So what i did was to create a .htaccess file in the root directory of massanti.com with the following contents:

<ifmodule mod_rewrite.c>
   RewriteEngine on
   RewriteCond %{REQUEST_FILENAME} !-f [NC]
   RewriteCond %{REQUEST_FILENAME} !-d [NC]
   RewriteRule ^(.*)$ http://blog.massanti.com/$1 [R=301,L]
</ifmodule>

Let’s analyze this:

  • The ifmodule encapsulation is self explanatory, it basically means “do whatever you find inside me only if the mod_rewrite module is enabled”.
  • The first RewriteCond line takes whatever url parameter we get and checks if a real file exists, while the 2nd line does the same, but for directories.
  • The “[NC]” bit in each of the conditions tells mod_rewrite to ignore casing.
  • The RewriteRule line will only execute IF ANY of the 2 RewriteCond conditions is TRUE (if no real file and no real directory is found in the file system matching the URL request), AND if that happens, it will redirect the client’s browser or search engine to the new page (blog.massanti.com/ + the requested URL) and it will send a 301 permanent redirect header, telling the browser and search engines that the redirection is permanent, hence, causing most search engines, browsers and RSS readers to automatically update all the URL’s to the new ones.

No comments yet, leave yours!.