Redirect non-www to www in .htaccess

后端 未结 13 1736
轻奢々
轻奢々 2020-11-22 05:51

I have this in my .htaccess file:

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com$1 [R=301,L]

but whenever I

13条回答
  •  终归单人心
    2020-11-22 06:15

    I believe the top answer successfully redirects non-www to www (ex: mysite.com -> www.mysite.com), but doesn't take into account wildcard subdomains, which results in:

    random.mysite.com -> www.random.mysite.com
    

    Here's a solution with/without HTTPS

    HTTP

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
    RewriteRule ^(.*)$ http%{ENV:protossl}://www.mysite.com/$1 [L,R=301] 
    

    HTTP/HTTPS

    RewriteEngine On
    
    RewriteCond %{HTTPS} =on
    RewriteRule ^(.*)$ - [env=protocol:https]
    
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)$ - [env=protocol:http]
    
    RewriteCond %{HTTP_HOST} !www.mysite.com$ [NC]
    RewriteRule ^(.*)$ %{ENV:protocol}://www.mysite.com/$1 [L,R=301]
    

    *note: I haven't tested https because I don't currently have a cert to test, but if someone can verify or optimize what I have that would be awesome.

提交回复
热议问题