Softpress

Apache mod_rewrite: Make your Server more Flexible

Question
I'm planning to change my site to use Server Side Includes, which will mean that I have to change all the filenames from file.html to file.shtml. But this will mean that bookmarks (and more importantly, search engine rankings) will break. How can I avoid this problem?

Answer
It won't be a problem at all if your ISP uses the Apache Web server (most do).

Ask your ISP if they have enabled URL-rewriting for your account, and if they allow you to modify your Web root through an .htaccess file.

If so, create a plain text file named .htaccess (leading period is important) in the same directory as your site files, containing these lines:
RewriteEngine On
RewriteBase /path/from/web/root/
RewriteRule ^(.*)(.html)$ $1.shtml [L,R,PERMANENT]
In the above example, you only need to provide the RewriteBase if your .htaccess file is in a sub-folder to your main site root folder. For example, if your main web site (http://www.domain.com) is contained in a folder on your server, and your .htaccess file is also directly inside this folder, you won't need it. But if you are enabling this trick for only one folder within your site, for example, in "http://www.domain.com/myfolder/", you will need to set the RewriteBase to "/myfolder/", and put the .htaccess file within that folder.

The RewriteRule works like this: the first set of parentheses capture the filename and save it as a variable named $1. The second set of parentheses capture the dot and the extension. In this example, that is .html, but it could just as easily be .php or another extension. The rule then re-writes the URL and forces it back to the browser, using the filename (represented by $1), but then tacking on .shtml to the end of it. Finally, the flags inside the square brackets tell the rewrite engine to also do the following:

L: This is the Last rule to follow before redirecting. Useful if you have many rules, but you only want one to be followed.

R: Do an external redirect, attaching http://servername:port/ to the URL when creating the redirect header.

PERMANENT: Send the Moved-Permanently header that will cause a search engine to re-spider your site with the new URLs.

You will not need to re-start the Web server. The very next access to the site will see the change.


Related Articles

Attachments

No attachments were found.

Article Details

Last Updated
24th of November, 2008

Would you like to...

Print this page  Print this page

Email this page  Email this page

Post a comment  Post a comment

 Subscribe me

Subscribe me  Add to favorites

Remove Highlighting Remove Highlighting

Edit this Article

Quick Edit

Export to PDF


User Opinions

100% thumbs up 0% thumbs down (1 vote)

How would you rate this answer?




Thank you for rating this answer.

Continue