Search code examples
.htaccesshttp-redirectmod-rewritehttpsno-www

htaccess redirect http and www to https non-www with one rewrite rule not working so


I had the following .htaccess code working with 2 RedirectRules:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ https://%1/$1 [NE,R=301,L]
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_METHOD} !=POST
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

But I want to make an optimized solution. I came up with this based on my previous htaccess, but this is not working, and I would like to know why?

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

Another variation (preferred), not working:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC,OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !=https
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%1/$1 [NE,R=301,L]

Browser gives "Corrupted Content Error" message.


Solution

  • You may be able to use this combined rule:

    ## remove www and turn on https in same rule
    RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]
    

    Make sure to use a new browser for testing the change.