02 September 2010

Apache and automatic redirection

Say we need to rename one of our files but the page has a lot of incoming links from third party websites. We don't want to loose that traffic and sent a 404 error page to the user. One way to solve it is to use Apache redirection from the old URL path to the new file. The new URL for the request file (page, image, resource) is returned to the client which will attempt to fetch the page again using the new address. The redirection can be achieved either in the .htacess file or in the virtual host in Apache using mod_alias.

To rename a file, we use its absolute file system path and the old URL next. Example for a Linux machine:
Redirect /location/from/root/file.ext http://www.example.com/index.html

Apache also allows us to rename folders:
Redirect /oldir http://www.newsite.com/newdir

If we want to make the redirect permanent:
Redirect permanent /oldir http://www.newsite.com/newdir
This will send a HTTP status of 301 telling the client (browser) that the resource has moved for good.

By default, the status is 302, but temp can be used, it makes it more readable for us once we have a lot of redirects.

If we removed a resource for good and we won't replace it nor do we wish to sent the user to a specific page, we use the status gone. The HTTP stauts 410 will be sent indicating the resourse has been removed.

If we replaced a resource for another, say we upgrade a library file which contains the version in the name, and we don't want to keep the older version available online, we can sent the See Other status that will indicate that the resource has been replaced.

We can also use Apache mod_rewrite to atchive the redirects.
RewriteEngine On
RewriteRule /.* http://www.example.com/ [R]
This would redirect any request to the server to a new website, or to the root of the website if the domain was example.com.