Generic htaccess redirect www to non-www

581,621

Solution 1

But if we need to do this for separate http and https:

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

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

Solution 2

Redirect non-www to www (both: http + https)

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]

Solution 3

If you want to do this in the httpd.conf file, you can do it without mod_rewrite (and apparently it's better for performance).

<VirtualHost *>
  ServerName www.example.com
  Redirect 301 / http://example.com/
</VirtualHost>

I got that answer here: https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost/120507#120507

Solution 4

Here are the rules to redirect a www URL to no-www:

#########################
# redirect www to no-www
#########################

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

Here are the rules to redirect a no-www URL to www:

#########################
# redirect no-www to www
#########################

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

Note that I used NE flag to prevent apache from escaping the query string. Without this flag, apache will change the requested URL http://www.example.com/?foo%20bar to http://www.example.com/?foo%2250bar

Solution 5

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ https://%1/$1 [R]

The RewriteCond captures everything in the HTTP_HOST variable after the www. and saves it in %1.

The RewriteRule captures the URL without the leading / and saves it in $1.

Share:
581,621
deepwell
Author by

deepwell

Lead high performing software organizations.

Updated on September 25, 2021

Comments

  • deepwell
    deepwell over 2 years

    I would like to redirect www.example.com to example.com. The following htaccess code makes this happen:

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

    But, is there a way to do this in a generic fashion without hardcoding the domain name?