I have the following htaccess code:
<IfModule mod_rewrite.c> RewriteEngine On RewriteCond !{HTTPS} off RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule>
I want my site to be redirected to https://www.
with HTTPS, and enforcing the www.
subdomain, but when I access http://www.
(without HTTPS), it does not redirect me to https://www
with HTTPS.
E.g.: RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^www.example.com/$ [NC] RewriteRule ^(. *)$ http://www.example.com [R=301,L] ... @BobbyS I used the solution in this article. It redirects www and HTTP to non-www HTTPS and also handles the trailing / .
To first force HTTPS, you must check the correct environment variable %{HTTPS} off
, but your rule above then prepends the www.
Since you have a second rule to enforce www.
, don't use it in the first rule.
RewriteEngine On RewriteCond %{HTTPS} off # First rewrite to HTTPS: # Don't put www. here. If it is already there it will be included, if not # the subsequent rule will catch it. RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Now, rewrite any request to the wrong domain to use www. # [NC] is a case-insensitive match RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
When behind some forms of proxying, whereby the client is connecting via HTTPS to a proxy, load balancer, Passenger application, etc., the %{HTTPS}
variable may never be on
and cause a rewrite loop. This is because your application is actually receiving plain HTTP traffic even though the client and the proxy/load balancer are using HTTPS. In these cases, check the X-Forwarded-Proto
header instead of the %{HTTPS}
variable. This answer shows the appropriate process
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With