Apache rewrite rules from your naked domain to a www prefix


Many web applications either choose to use a naked domain, while others prefer to use a "www" prefix in front of their domain.

From a SEO point of view, using a single point of entry would mean all your analytics will always use the correct url. A huge benefit I would like to add.

When I search the interent for a solution, I often stumble upon the following to redirect rule.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,L] 

My problem with this solution is I cannot reuse this approach as I need to modify the domain settings for each project.

I love to use the following rewrite rule on my Apache web server. On production I've put this in my VirtualHost directive, but on my development and testing servers I've put it in .htaccess.

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

The nicest bit of this sample it allows you to reuse these settings on each domain you're working on, no matter if you're using plain HTTP or adding SSL security to it.

Let me know if this example works better for you too.

Comments

Popular Posts