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

.htaccess guidance

.htaccess is a special Apache file that tells your website how to function. You can edit the...

301 Permanent redirects for parked domain names

If you have several domain names parked/pointed at your site it is a good idea to create...

Redirect URLs using .htaccess

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

Common Apache mod_rewrite and examples

I am going to give you some common dot-htaccess codes our customers love. Please remember we do...

Can you provide a custom package for me?

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