htaccess force https and redirect www to non-www, but no other subdomains

后端 未结 6 727
醉话见心
醉话见心 2020-12-01 11:03

I know there are many similar threads, but none of them seems to match my exact problem. Here is what I’m trying to do:

(1) http://www.mydomain.com/ -> ht         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 11:21

    Non of the examples worked for me, they just seemed to get stuck in a loop, the following works though.

        # 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 will prevent a 3rd redirect in some cases.

    If you want to use a sub domain (anything other than www.) just remove the first ruleset.

    So for sub domains all you need is

        # match non https and redirect to https
        RewriteCond %{HTTP:X-Forwarded-Proto} !https
        RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
    

    I use Cloudways services and I've found this to be the only thing that works

提交回复
热议问题