Archive for Tips and tricks

.htaccess redirect from non-www to www

.htaccess is a useful tool of the apache but you’re using it so often that it needs learning and considering this, I always find myself needing a .htaccess redirect on the projects I’m working on.
Currently I’m working on a project that needs .htaccess redirect from the name of the domain without the www. prefix to the one with the prefix.

So here’s how it should look like:


Options +FollowSymLinks
RewriteEngine On

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

In your case you should copy the above mentioned example and modify both “dincaradu.com” and “www.dincaradu.com” with the actual domain name on which you are installing this .htaccess option.
It is a 301 redirect so it’s search engine friendly, better than any javascript redirect.

The .htaccess Rewrite option has a few options that you can set depending on the type of the redirect or rewrite of the URL. The options are the following:

NC – This means no-case and says that the condition should not be case sensitive.
R=301 – This means to redirect rather than rewrite with an HTTP status of 301.
L – This means it is the last rule that should be processed. Therefore, if this line is executed, everything else following in the .htaccess file will be skipped.
^ – In a regular expression, this means the beginning of the line.
$ – In a regular expression, this means the end of the line.
(.*) – In a regular expression, .* means to match anything. The () around the expression is so you can use the match later using varaibles like $1, $2, etc.

Further clarification on this matter you can find in the documentation on the official site of apache:
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteCond
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteRule