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:
1 | RewriteEngine on |
2 | RewriteCond %{QUERY_STRING} id=1 |
3 | RewriteRule ^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:
1 | RewriteEngine on |
2 | RewriteCond %{QUERY_STRING} id=1 |
3 | RewriteRule ^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:
1 | RewriteEngine On |
2 | RewriteRule ^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:
1 | RewriteEngine On |
2 | RewriteRule ^([^/]+)/?$ 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:
1 | RewriteEngine On |
2 | RewriteRule ^/?category/([^/]+)/?$ index.php?category=$1 [L,QSA] |
6. Domain change – redirect all incoming request from old to new domain (retain path)
1 | RewriteEngine on |
2 | RewriteCond %{HTTP_HOST} ^example-old\.com$ [NC] |
3 | RewriteRule ^(.*)$ 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:
1 | RewriteRule ^(.*)$ http://www.example-new.com/ [R=301,L] |
Nguồn: https://gerillafilm.se/
Comments
Post a Comment