Apache htaccess : Redirect Old URLs to new URLs after Rewrite URLs have been applied
.htaccess (Hypertext Access) files is a configuration file on Apache web server. It allows users to do many powerful features just by writing few lines. As of wikipedia, the most common usage of .htaccess files are follows:
- Authorization, authentication
- Customized error responses (ErrorDocument)
- Rewriting URLs (mod_rewrite)
- Cache Control
Since this is a topic which has been widely blogged, I decided to write a topic which is hard to find, and followed by links to other blogger's site (which explains htaccess extensively).
The following is a topic rarely blogged/discussed:
Redirect Old URL's to new URL's after Rewrite URLs have been applied
Often times I have seen sites which recently implemented Rewrite URLs, have not taken the time to redirect Old requests to the new URL. To clarify, for example, if a site's URL was previously like the following:
http://www.mydomain.com/fishing/blog.php?blog=78&category=31
People only tend to add the following on the Rewrite URLs:
RewriteRule ^fishing/([0-9]+)/([0-9]+).html$ fishing/blog.php?blog=$1&category=$2 [L]
Now, with the Rewrite URLs, the URL now looks like:
http://www.mydomain.com/fishing/31/78.html
Or Some writes the Title on the URL itself (for better SEO), like the following:
http://www.mydomain.com/fishing/31/78/cat-fishing-michigan
Note*: for above case, just be sure to strip out the stop words, otherwise it can damage the SEO Ranking.
However, if a visitor had a previous URL bookmarked, and if tries to visit (http://www.mydomain.com/fishing/blog.php?blog=78&category=31), he will still visit the old URL with the contents displayed and wont be redirected to new URL.
In this case, its better to redirect Old URLs to the Newly written URL with a 301 (Permanently Moved) Status. This can be achieved by adding the following lines:
RewriteCond %{THE_REQUEST} fishing/blog\.php\?content=([0-9]+)&category=([0-9]+)[^\ ]*\ HTTP/ [NC] RewriteRule fishing/blog\.php$ /fishing/%2/%1.html? [R=301,L]
The 1st line of code intercepts any URL request of the old pattern (/fishing/blog.php?...) and rewrites it into the new pattern with a 301 (Permanently Moved) status. This is useful for SEO.
For a thorough list of htaccess features, please check out the following URLs:
- Stupid htaccess Tricks
- 16 Useful htacess Tricks and hacks
Good post my friend...
Can you add the references to basic url re-write rules that you were talking in the beginning?
Post new comment