URL redirection examples with mod_rewrite

Here are a few examples you can use to redirect visitors or rewrite URLs on your site. The examples all make use of Apache's mod_rewrite module. The basic shell for a redirect/rewrite is as follows, and should go in the .htaccess file in the root of your website:

<IfModule mod_rewrite.c>
  RewriteEngine on
  # Redirect goes here
</IfModule>

This checks to see whether the mod_rewrite module is available to you, and turns on the rewrite engine.

The first example is a redirect in its simplest form. It redirects visitors from /oldpath to /newpath:

RewriteRule ^oldpath /newpath [L,R=301]

R=301 signifies that the redirect is permanent. This is useful because it instructs search engines to update the URL for your page without compromising your SEO results.

You can also redirect users from /oldpath to /newpath at a different URL:

RewriteRule ^oldpath http://example.com/newpath [L,R=301]

The following example will redirect visitors requesting a specific host name to a new host name. It checks for visitors requesting either oldhost.com or www.oldhost.com and redirects them to www.newhost.com and appends the query string to the end of the target URL:

RewriteCond %{HTTP_HOST} ^(www\.)?oldhost\.com$ 
RewriteRule ^(.*)$ http://www.newhost.com/$1 [L,R=301]

For example, a user visiting http://www.oldhost.com/about will be redirected to http://www.newhost.com/about.

The following example ensures the www. prefix is present in your URL:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This ensures the www. prefix is NOT present in your URL:

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

This example rewrites all requests to a subdirectory on your site. This is not a redirect, but is completely transparent to the user, i.e. it will appear to the user as though they are on the original URL, but the files will be retrieved from within the subdirectory. Replace subdirectory with the name of your subdirectory:

RewriteCond %{REQUEST_URI} !subdirectory/
RewriteRule ^(.*)$ subdirectory/$1 [L,QSA]

In the above example [QSA] ensures the original query string is retained.

If you have multiple domains with different TLDs pointing to your website, e.g. bluepiccadilly.com, bluepiccadilly.net, etc., and you want to ensure that the site is served only from the primary TLD (bluepiccadilly.com in this case), you can use the following example to redirect visitors:

RewriteCond %{HTTP_HOST} !\.com$ [NC]
RewriteRule ^(.*)$ http://www.bluepiccadilly.com/$1 [L,R=301]

The first line checks to see if the URL ends in a .com. If not, the visitor is redirected.

For reference, Cheatography maintains a really good mod_rewrite cheat sheet.