我在这里看到了一些类似的问题,但似乎没有答案。我似乎无法弄清楚这一点。这是我的代码:
# enable basic rewriting
RewriteEngine on
# enable symbolic links
Options +FollowSymLinks
# Primary Domain - Force the use of "https"
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
# Primary Domain - Force the use of "www"
RewriteCond %{http_host} ^example.org [nc]
RewriteRule ^(.*)$ https://www.example.org/$1 [r=301,nc]
# Primary Domain - .com to .org
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]
# Primary Domain - .net to .org
RewriteCond %{HTTP_HOST} ^example.net$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.example.net$ [NC]
RewriteRule ^(.*)$ https://www.example.org/$1 [R=301,L]
所以无论何时我去 www.example.org
或 http://www.example.org
它都不会重定向。这就是让我沮丧的地方。如果我转到 example.org 或任何其他重定向,它仍然有效。我设置错了吗?
另外,在它写着“HTTP_HOST”的地方,我要保持原样吗?比如我是否将其替换为我的 http 主机?
最佳答案
Amie,如果你想强制使用 www
和 https
,你可以检查是否缺少 www。或检查 https
是否为 not On
然后重定向。所以无论哪种方式它都会重定向。示例。
# Primary Domain - Force the use of "https" and www
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTPS} !^on$
RewriteRule ^(.*)$ https://www.mydomain.org/$1 [R=301,L]
将 mydomain.org 替换为您的域。
然后你就可以拥有这样一个htaccess文件了。我采用了最后两条规则并将它们组合在一起,这样你就有了一个更小的 htaccess 文件。
# enable basic rewriting
RewriteEngine on
# enable symbolic links
Options +FollowSymLinks
# Primary Domain - Force the use of "https" and www
RewriteCond %{HTTP_HOST} !^www\. [OR]
RewriteCond %{HTTPS} !^on$
RewriteRule ^(.*)$ https://www.mydomain.org/$1 [R=301,L]
# Primary Domain - .com to .org Or .net to .org
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain\.(net|com)$ [NC]
RewriteRule ^(.*)$ https://www.mydomain.org/$1 [R=301,L]
Also, where it says "HTTP_HOST", do I leave it as is? Like do I replace it with my http host?
%{HTTP_HOST}
是一个变量,其中包含从浏览器发送的带有 Http header 的主机。因此,如果有人请求 http://mydomain.org/somepage.php
,则变量 %{HTTP_HOST}
将包含 mydomain.org
。你不改变它。您可以使用它来匹配事物或设置规则中的条件。希望这能回答你的问题。
关于apache - 通过 .htaccess 将 http 重定向到 https 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18627024/