How to redirect non-www to www without hardcoding using .htaccess?
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
...causes a perfect, non-hardcoding 301 redirect from "www to non-www", what would the exact opposite look like?
EDIT:
According to Prix' post I've changed the .htaccess
file to the following:
Options +FollowSymLinks
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
</IfModule>
As already mentioned, this redirects to http://www./
unfortunately. Who can help?
Prix almost had it. When you negate the RewriteCond
(with !
) it doesn't capture so %1
is empty. Two possible solutions:
Dummy RewriteCond
:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.+)$ [NC]
RewriteRule ^/(.*)$ http://www\.%1/$1 [R=301,L]
%{HTTP_HOST}
in RewriteRule
:
RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteRule ^/(.*)$ http://www\.%{HTTP_HOST}/$1 [R=301,L]
In summation, a clean, tested version of the code:
This works (for me) to redirect www to non-www
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
Either one of these work (for me) to redirect non-www to www
RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://www\.%{HTTP_HOST}/$1 [R=301,L]
or
RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteCond %{HTTP_HOST} ^(.+)$ [NC] RewriteRule ^(.*)$ http://www\.%1/$1 [R=301,L]
RewriteCond %{HTTP_HOST} !^www\.(.+)$ [NC]
RewriteCond %{HTTP_HOST} ^(.+)\.(.+)$ [NC]
RewriteRule ^(.*)$ http://www\.%2/$1 [R=301,L]
the !
means if it does not start with "www..." then send it to www.%1
which is the (.+)