Redirecting Dynamic URL using mod_rewrite

What do you do when you need to move servers or web-files to a different domain or directory, especially if you need to be moving dynamic content. How would you prevent down-time? This is not an end all solution, but Apaches' module mod_rewrite comes to the rescue of redirecting URLs.

Below are the steps that was taken to move web-files to a different servers.

1. Create a temporary unused sub-domain to point to the new servers IP address.

2. Allow for a day before you migrate your content to let the subdomain resolve.

3. Setup rewrite rule to redirect your current domain to the temporary domain after migrating content.

4. Change the Primary and Secondary NameServers for the domain to point to the new location.

5. Keep the redirection up for a while until the NameServers are fully resolved.

Below is an example of what was used:

# this tells the web server to allow rewriting for this directory
RewriteEngine On                                                                             

# check the hostname to apply the redirection to
RewriteCond %{HTTP_HOST} domain.com [OR]
RewriteCond %{HTTP_HOST} www.domain.com

# describe the pattern to look for, and how to rewrite it 
RewriteRule ^(.*)$ http://temp.domain.com/$1 [R]

All rewrite rules are contained in the .htaccess file. The rewrite rules cover all the files in the directory that contains the .htaccess file.

In general, each RewriteRule line specifies a pattern to look for, and a replacement text. The patterns can be very complicated — the rules have the full power of Unix Regular Expressions (ie. grep), but the example shown above will serve most people.

The "[R]" in the rewrite rule shown above tells the web server to redirect the user's browser to the new URL. This is useful because the browser will show the new URL, and saving a bookmark will always lead to the new location.

Leaving the [R] off the line will also display the new URL, but a bookmark saved from the resulting page will continue to use the original (non-rewritten) URL. This would be useful if you want to preserve an easy-to-remember URL, but also want the ability to change it in the future.

Reference the Apache Manual for more information and apply it to other areas of your web-mastering skills. The possibilities are endless.

Comment