www and non-www .htaccess rewrite rules

Here's the complete library for use in .htaccess:

# Redirect if NOT www.example.com (exactly) to www.example.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

-or-

# Redirect if example.com (case-insensitive) to www.example.com
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

If you want to do the opposite, i.e. redirect www to non-www

# Redirect if NOT example.com (exactly) to example.com
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^example\.com
RewriteRule (.*) http://example.com/$1 [R=301,L]

-or-

# Redirect if www.example.com (case-insensitive) to example.com
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule (.*) http://example.com/$1 [R=301,L]

All differences between this and what you posted are intentional. Select the code snippet that matches your needs. Note that using the "NOT " versions precludes the use of subdomains other than "www", but is more comprehensive.For use in httpd.conf, change the rule pattern from "(.*)" to "^/(.*)".

If the non-canonical www domain already works --that is, if it returns the same content as the non-www domain-- then no changes to your ServerName/ServerAlias configuration are necessary.

  • 15 Users Found This Useful
Was this answer helpful?

Related Articles

Can you provide a custom package for me?

Yes, most definitely. Simply open up a helpdesk ticket in the Sales department or contact us...

Redirect URLs using .htaccess

Sometimes you need to redirect some URL and/or page on your site to another one.The feature is...

Force SSL/https using .htaccess and mod_rewrite

Sometimes you may need to make sure that the user is browsing your site over a secure...

Change PHP variables using .htaccess

If you need to change the way your PHP is working you can do that using .htaccess.Please, note...

Block Bad robots, spiders, crawlers and harvesters

There are lots of examples across the internet that use ModRewrite. We will provide such an...