Mod rewrite for 301 redirects

301 redirects are essential if you port a site that ranks well to a new page address or domain. It is common on a LAMP platform to use the htaccess file and mod rewrite to acheive this. Here are some useful examples of mod rewrite rules to help you along the way.

With RewriteEngine On
and in RewriteRule
^home\.php$ # Just file itself
^home\.php(.*)$ # File plus zero or more chars
^home\.php(.{0,})$ # File plus zero or more chars
^home\.php(.{0,28})$ # File plus zero to 28 (or whatever) chars
^home\.php(.+)$ # File plus one or more chars
^home\.php(.{1,})$ # File plus one or more chars
^home\.php(.{1,28})$ # File plus one to 28 (or whatever) chars
^home\.php\?var=val$ # File with specific query string
^home\.php([\?]([a-zA-Z0-9]+)=([a-zA-Z0-9]+))$ # File with regex for basic query
^home\.php#overHere$ # File with Hash part

So for example use the following script with the above expressions:

ReWrite Engine On

Rewrite Rule ^home\.php([\?]([a-zA-Z0-9]+)=([a-zA-Z0-9]+))$ http://www.new-domain.com/$i

This will rewrite any url on the old domain of the form http://www.old-domain.com/home.php?something=value to the new url: http://www.new-domain.com/home.php?something=value

With variations on the expressions above you can acheive most of what you are after to pass on that vital link juice.

Tags: , , ,

3 Responses to “Mod rewrite for 301 redirects”

  1. james bailey says:

    I have to say I think your example gives a 302 redirect. To get a 301 you need to append [R=301,L] to the line, or more simply using your examples you can:

    Redirect permanent ^home\.php([\?]([a-zA-Z0-9]+)=([a-zA-Z0-9]+))$ http://www.new-domain.com/$i

    or

    Redirect 301 ^home\.php([\?]([a-zA-Z0-9]+)=([a-zA-Z0-9]+))$ http://www.new-domain.com/$i

  2. james bailey says:

    Actually your example give neither a 302 or a 301 me thinks

  3. james bailey says:

    OK last comment, your example does give a 302

Leave a Reply