Search code examples
.htaccesshttpsno-www

Why my htaccess for no-www and https doesn't work?


I've a problem with my .htaccess file. I want to redirect no-www to www and HTTP to HTTPS.

I've tried these files but they don't work...

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

RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,R=301,L]

And

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301] 

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

Can you help me?


Solution

  • The initial problem was that .htaccess files were not enabled in the server config. After setting AllowOverride All in the server config to enable .htaccess files, this resulted in a redirect loop...

    You are getting a redirect loop because the HTTPS server variable is reporting "off" when HTTPS is requested. This implies you have a front-end proxy that is handling the SSL connection, and this is confirmed by the fact that the X-Forwarded-Proto HTTP request header (that your application server is seeing) is set to "https". (The X-Forwarded-Proto header is set by the proxy server as the request passes through.)

    This implies that the "private" connection between this proxy and your application server is over plain HTTP. But the connection between the proxy and the client is secured by HTTPS. This isn't necessarily a problem, however, it means you need to adjust your directives to check the X-Forwarded-Proto HTTP request header instead of the HTTPS server variable.

    For example:

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

    Make sure you clear your browser cache before testing. It is often preferable to test with 302 (temporary) redirects and only change to 301 (permanent) when you are sure it's working OK - to avoid caching issues.