http 到 https,www 到非 www 并尊重 url

http to https, www to non www and respect urls

我想将 http 重定向到 https,将 www 重定向到非 www。

案例:

http://example.com/my/url
http://www.example.com/my/url
https://example.com/my/url
https://www.example.com/my/url

结果

https://example.com/my/url
https://example.com/my/url
https://example.com/my/url
https://example.com/my/url

我当前的 htaccess 文件:

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

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

问题:

它重定向到 https://example.com/index.php

我希望它尊重 url https://example.com/my/url

我发现了很多问题,但我还没有找到完整的解决方案。事实上,上面的 htaccess 代码是唯一在大约 10 次尝试中运行良好的代码。

您可以使用这条规则删除 wwwhttp -> https:

RewriteEngine On

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

# rest of rules go here ....

如果您遇到重定向过多的问题,请尝试将第二行替换为:
RewriteCond %{ENV:HTTPS} !on

重要的是将此规则作为您的第一条规则并在测试前清除您的浏览器缓存。