0

如何仅将主页重定向到 https 而没有 www?

http://www.mywebsite.com
http://mywebsite.com
https://www.mywebsite.com

上述所有 URL 都应重定向一次:

https://mywebsite.com

子目录中的所有内容都应保持不变

https://mywebsite.com/website-in-progress

我正在尝试我找到的各种代码,但我没有找到任何适用于所有情况的代码。

编辑:这似乎在视觉上工作得很好,问题是某些 URL 有多个重定向

RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

这样做的结果是:

- https://mywebsite.com/ - OK
- https://www.mywebsite.com/ - not desirable, redirects first to http://mywebsite.com and then to https://mywebsite.com
- http://www.mywebsite.com/ - not desirable, redirects first to https://www.mywebsite.com and then to https://mywebsite.com
- http://mywebsite.com/ - OK, redirects once to https://mywebsite.com/
4

1 回答 1

1

您可以将此规则用作最重要的规则:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} !on
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^/?$ https://%1% [R=301,L]
于 2018-12-21T08:24:39.793 回答