.htaccess redirect both naked http and https to www https

◇◆丶佛笑我妖孽 提交于 2020-01-05 05:31:09

问题


I have similar issue on one of my domains. I have SSL cert installed both for naked and www-domain.

Now, however I want to redirect both naked http://domain.com and https://domain.com to https://www.domain.com.

I have this rules in my .htaccess, but it covers redirect when you visit site explicitly with https://domain.com, but, when visiting http://domain.com, it redirects to http://www.domain.com instead https://www.domain.com.

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

回答1:


You should replace your existing rule with this rule:

RewriteEngine On

# add www and convert http to https
RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

Keep this rule right below RewriteEngine On line and clear your browser cache before testing.




回答2:


I personally would lay it out like this, this will force WWW and HTTPs for everything.

RewriteEngine On

#Force WWW on everything
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

#Force HTTPS on everything
RewriteCond %{HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]


来源:https://stackoverflow.com/questions/38227609/htaccess-redirect-both-naked-http-and-https-to-www-https

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!