问题原文
原帖链接 · imlost · CC BY-SA 4.0
When I use these lines in my .htaccess file, everything works well:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://example.com%{REQUEST_URI} [L,R=301]
Then I tried to make it work without manually writing the domain in the URL and tried these lines instead:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
But now there is an additional redirect when reached from www without https:
I don't understand why, I just replaced the domain with {HTTP_HOST}. When I do that, it redirects from http://www.example.com to http://example.com (since it is my main domain) then http://example.com to https://example.com
If I add this line: RewriteCond %{HTTP_HOST} !^www\. [NC] it does not change anything.
Why does it behave like that and how can I fix the .htaccess file to not having to manually write the URL and directly redirect http://www.example.com to https://example.com?
已采纳解答
原帖链接 · Stephen Ostermiller · CC BY-SA 4.0
If you always want to remove the www. from the host name then you should use your first set of rules that contain the domain name. That is because the {HTTP_HOST} variable contains the full host name including any subdomains. So when the site is accessed with http://www.example.com the HTTP_HOST is www.example.com. When you use that variable in the redirect, the www. is included.
If you really object to hard-coding your domain name in that rewrite rule, it might be possible to switch from HTTP_HOST to SERVER_NAME. The server name variable can be made to be your preferred host name as specified in your virtual host configuration, but only if UseCanonicalName on is on there as well. See What is the difference between HTTP_HOST and SERVER_NAME in PHP? Your virtual host configuration would have to be:
<VirtualHost *>
ServerName example.com
UseCanonicalName on
ServerAlias www.example.com
...
</VirtualHost>
You may not have such fine grain control over your virtual host directive. Many hosting packages such as cPanal and WHM write the config for you and don't let you modify it. I'd recommend sticking with your hard-coded domain name in your rewrite rule because it is easy to do and it works.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
