how to redirect www and non www to https for specific domain using htaccess

前端 未结 3 519
感情败类
感情败类 2021-02-09 20:21

I need to redirect www and non www to https. I have looked everywhere on stackoverflow but can\'t find quite what I\'m looking for.

The rules are:

  • example.
相关标签:
3条回答
  • 2021-02-09 20:46

    You can use the following rule to redierct non-www or www to https://www in just one redirection

    #redirect http non-www to https://www
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
    RewriteRule (.*) https://www.example.com/$1 [R=301,L]
    #redirect https non-www to www
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^example\.com$
    RewriteRule (.*) https://www.example.com/$1 [R=301,L]
    

    Clear your browser's cache before testing this rule.

    0 讨论(0)
  • 2021-02-09 20:54

    This is the only way it works for me - with !on instead of off and with %{ENV:HTTPS} instead of %{HTTPS}:

      #non-www. http to www. https
      RewriteCond %{ENV:HTTPS} !on
      RewriteCond %{HTTP_HOST} ^(www\.)?yourdomain\.com$
      RewriteRule (.*) https://www.yourdomain.com/$1 [R=301,L]
    
      #non-www. https to www. https
      RewriteCond %{ENV:HTTPS} on
      RewriteCond %{HTTP_HOST} ^yourdomain\.com$
      RewriteRule (.*) https://www.yourdomain.com/$1 [R=301,L]
    
    0 讨论(0)
  • 2021-02-09 20:54
    #First rewrite any request to the wrong domain to use the correct one (i.e. www.)
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    #Now, rewrite to HTTPS:
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    0 讨论(0)
提交回复
热议问题