Force non-www and https via htaccess

前端 未结 3 1099
醉话见心
醉话见心 2020-12-14 08:53

I\'m trying to force a user to be redirected to the non-www website, and, force https.

I\'ve got this which sort of work, but doesn\'t force https, when http is ente

相关标签:
3条回答
  • 2020-12-14 09:16

    Based on Gumbo's comment : "the TLS/SSL connection is established and certificate is validated before it is handed down to HTTP and the HTTP redirection takes place" I gave this a try (which seems to work):

    RewriteEngine On 
    RewriteCond %{SERVER_PORT} 80 
    RewriteRule ^(.*)$ https://www.blahblah.com/$1 [R,L]
    
    RewriteCond %{HTTP_HOST} ^www\.blahblah\.com [NC]
    RewriteRule ^(.*)$ https://blahblah.com/$1 [L,R=301]
    

    please tell me if there is something wrong with this approach.

    0 讨论(0)
  • 2020-12-14 09:22

    Try this rule:

    RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR]
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(www\.)?(.+)
    RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]
    
    0 讨论(0)
  • 2020-12-14 09:33

    The only set of rules that works for me is the following

    # match any URL with www and rewrite it to https without the www
        RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
        RewriteRule (.*) https://%2%{REQUEST_URI} [R=301,L]
    
    # match non https and redirect to https
        RewriteCond %{HTTP:X-Forwarded-Proto} !https
        RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
    

    The order matters, it prevents a third redirect in some cases.

    0 讨论(0)
提交回复
热议问题