Ultimate .htaccess rewrite tutorial with 301 redirects

So, over the last couple of weeks I have moved several sites to new locations and publishing platforms which demands some redirects unless you wanna be a SEO killer. The examples below are mostly URLs with query strings which I either want to hide or make prettier. The fourth and fifth examples are quite useful when you want to create human readable URLs for APIs or web services.
Updated 22 November 2011.

1. Rewrite and redirect URLs with query parameters (files placed in root directory)

Original URL:
Desired destination URL:
.htaccess syntax:
1RewriteEngine on
2RewriteCond %{QUERY_STRING} id=1
3RewriteRule ^index\.php$ /path-to-new-location/? [L,R=301]

2. Redirect URLs with query parameters (files placed in subdirectory)

Original URL:
Desired destination URL:
.htaccess syntax:
1RewriteEngine on
2RewriteCond %{QUERY_STRING} id=1
3RewriteRule ^sub-dir/index\.php$ /path-to-new-location/? [L,R=301]

3. Redirect one clean URL to a new clean URL

Original URL:
Desired destination URL:
.htaccess syntax:
1RewriteEngine On
2RewriteRule ^old-page/?$ $1/new-page$2 [R=301,L]

4. Rewrite and redirect URLs with query parameter to directory based structure, retaining query string in URL root level

Original URL:
Desired destination URL:
.htaccess syntax:
1RewriteEngine On
2RewriteRule ^([^/]+)/?$ index.php?id=$1 [QSA]

5. Rewrite URLs with query parameter to directory based structure, retaining query string parameter in URL subdirectory

Original URL:
Desired destination URL:
.htaccess syntax:
1RewriteEngine On
2RewriteRule ^/?category/([^/]+)/?$ index.php?category=$1 [L,QSA]

6. Domain change – redirect all incoming request from old to new domain (retain path)

1RewriteEngine on
2RewriteCond %{HTTP_HOST} ^example-old\.com$ [NC]
3RewriteRule ^(.*)$ http://www.example-new.com/$1 [R=301,L]
If you do not want to pass the path in the request to the new domain, change the last row to:
1RewriteRule ^(.*)$ http://www.example-new.com/ [R=301,L]

Comments

Popular Posts