.htaccess redirect www to non-www with SSL/HTTPS
I've got several domains operating under a single .htaccess
file, each having an SSL certificate.
I need to force a https
prefix on every domain while also ensuring www
versions redirect to no-www
ones.
Below is my code; it doesn't work:
RewriteCond %{HTTP_HOST} ^www.%{HTTP_HOST}
RewriteRule ^.*$ https://%{HTTP_HOST}%{REQUEST_URI}/$1 [R=301,L]
What I want to achieve is to: redirect something like https://www.example.com
to https://example.com
.
What am I doing wrong and how can I achieve it?
www to non www with https
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Ref: Apache redirect www to non-www and HTTP to HTTPS
http://example.com
http://www.example.com
https://www.example.com
to
https://example.com
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
If instead of example.com you want the default URL to be www.example.com, then simply change the third and the fifth lines:
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,NE,R=301]
Your condition will never be true, because its like "if (a == a + b)".
I'd try the following:
RewriteCond %{HTTP_HOST} ^www\.(.*)
RewriteRule ^.*$ https://%1/$1 [R=301,L]
This will capture "google.com" from "www.google.com" into %1, the rest in $1 and after that combining the 2, when HTTP_HOST starts with www (with or without https).
To enforce non-www and https in a single request, you can use the following Rule in your htaccess :
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\. [OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [NE,L,R]
This redirects http://www.example.com/ or https://www.example.com/ to ssl non-www https://example.com/ .
I am using R Temp Redirect flag for testing purpose and to avoid browser caching. If you want to make the redirect permanent , just change the R flag to R=301 .