简体   繁体   English

始终使用htaccess通过www优化重定向到https

[英]Redirect to https always with www optimization using htaccess

I need to redirect everything to my domain to use https://www and below is the .htaccess I am currently using: 我需要将所有内容重定向到我的域以使用https:// www ,以下是我当前使用的.htaccess:

RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

It is working but it makes 2 redirects to the browser one if missing the www and the second if missing the secure which is slow of course and may be bad. 它正在工作,但是如果没有www,它将进行两次重定向到浏览器;如果缺少安全性,则进行第二次重定向,这当然很慢并且可能很糟糕。

What I want or my question is can this be reduced to single redirect rule to make it add both the www and the https in one rule. 我想要的还是我的问题是,可以将其简化为单个重定向规则,以使其在一个规则中同时添加www和https。

This online test tool shows 2 redirects https://varvy.com/tools/ : 此在线测试工具显示了2个重定向https://varvy.com/tools/

Final status code: 200
2 Redirect(s)
http://domain.com
301 redirect
https://domain.com/
https://domain.com/
301 redirect
https://www.domain.com/

Any good optimizations to this code. 对此代码进行任何好的优化。

You can use: 您可以使用:

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

2 rules but never more than one redirection 2条规则,但不能超过一个重定向

You can use just 1 single rule 您只能使用1条规则

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

non-www to www redirect is not needed here because you want to redirect both versions to https://www . 这里不需要非www到www重定向,因为您要将两个版本都重定向到https:// www

Clear your browser's cache before testing this. 在测试之前,请清除浏览器的缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM