e premte, 21 shtator 2007

Apache mod_rewrite and 301 redirection

One of the most powerful Apache modules is the mod_rewrite, which allows you to 'rewrite' URLs. By rewriting a URL, you can completely control its new destination. Another bonus of using mod_rewrite is that since it works at the server level, it can be used to forward whole websites.

To use mod_rewrite, your server needs to support it. To find out, either use the PHP phpinfo() function or ask your hosting provider. Assuming you have mod_rewrite available, add the following code to your .htaccess file (more on that in a bit).

To forward mysite.com to www.mysite.com, use the following code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^mysite\.com [nc]
RewriteRule (.*) http://www.mysite.com/$1 [R=301,L]

To forward www.mysite.com to mysite.com, use the following code:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.mysite\.com [nc]
RewriteRule (.*) http://mysite.com/$1 [R=301,L]

The .htaccess file

The Apache webserver uses .htaccess files to tweak its configuration while the server is running. The .htaccess file is a very versatile tool, but misusing it can make your site malfunction, so be careful!

The placement of the .htaccess file limits it effects: if you put it in your document root, it affects all of your website, but if you put it in a subdirectory, it affects that subdirectory and everything in it.

The .htaccess file is a simple text file, so edit it using a simple good text editor. For recommendations, see the list of freeware I keep.

More tips about .htaccess in this SEOChat forum thread and this thread.

Nuk ka komente: