Force non-www and HTTPS in htaccess redirect results in too many redirects

后端 未结 1 1415
既然无缘
既然无缘 2020-12-10 08:12

I\'m trying to force non-www https in htaccess, but every example I find throws the error \"too many redirects\"

I want to redirect:

  • http://www.e
相关标签:
1条回答
  • 2020-12-10 08:52

    Adding the RewriteCond and RewriteRule you specify gives me ?off_example.com when using http:// or https://. Is that expected?

    No, that's not the expected result - that will be the problem. HTTPS should be on when accessed over https://.... If the HTTPS server variable is never set to "on" (or rather, never changes from "off") then your RewriteRule will result in a redirect loop.

    This suggests that the "Let's Encrypt addon in Plesk" is implemented via some kind of "proxy" (front-end) server? Your application server still responds over unencrypted HTTP to the proxy and the clients connection to the proxy is encrypted over HTTPS. At least, that's what it looks like - but your host should be able to confirm this.

    If this is the case then the proxy usually sets additional HTTP request headers with details about the client's connection. You should be able to examine the request headers that your application sees, but it is common for the X-Forwarded-Proto header to be set with the protocol that is being used ("http" or "https"). If this is the case then you can probably change your existing directives to something like the following instead:

    RewriteEngine On
    RewriteCond %{HTTP:X-Forwarded-Proto} !https [OR]
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteRule ^ https://example.com%{REQUEST_URI} [L,NE,R=301]
    

    Another, less common method is for the (front-end) server to set an HTTPS environment variable (possibly provided by mod_ssl?) instead - note that this is different to the similarly named HTTPS server variable, as mentioned above. This environment variable is accessed using the syntax %{ENV:HTTPS} in the mod_rewrite directive and, if set, contains the same value as would otherwise be provided by the HTTPS server variable. For example:

    RewriteEngine On
    RewriteCond %{ENV:HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteRule ^ https://example.com%{REQUEST_URI} [L,NE,R=301]
    
    0 讨论(0)
提交回复
热议问题