【问题标题】:I want to redirect all http requests to https, and all www requests to non-www我想将所有 http 请求重定向到 https,并将所有 www 请求重定向到非 www
【发布时间】:2013-04-24 23:46:27
【问题描述】:

这是我当前的 .htaccess 文件:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
</IfModule>

我想将所有http请求重定向到https,所有www请求重定向到非www,所有文件请求重定向到index.php

例如:

http://www.example.comhttps://example.com

https://www.example.comhttps://example.com

http://example.com/file.phphttps://example.com/index.php

除了 www 部分,一切似乎都正常工作。请帮忙?

【问题讨论】:

  • www 部分不是包含在HTTP_HOST 中吗?

标签: .htaccess mod-rewrite


【解决方案1】:

http://www.example.comhttps://example.com
https://www.example.comhttps://example.com
http://example.com/file.phphttps://example.com/index.php

也许这会起作用:

RewriteEngine On

# Remove www from https requests. 
# Next 3 lines must be placed in one .htaccess file at SSL root folder, 
# if different from non-ssl.
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST}  ^www\.(.+) [NC]
RewriteRule ^(.*) https://%1/$1 [R=301,L]

# Redirect all http to https
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (?:www\.)?(.+)  [NC]
RewriteRule ^(.*) https://%1/$1     [R=301,L]

如果不行,换一个试试

RewriteCond %{HTTPS} offon

RewriteCond %{HTTP:X-Forwarded-SSL} offon

【讨论】:

    【解决方案2】:

    您可以添加处理 www 部分的附加规则

    RewriteCond %{HTTP_HOST} ^www\.(.+)$
    RewriteRule ^ https://%1%{REQUEST_URI} [L,R]
    

    RewriteCond 捕获www. 之后的所有内容,并将RewriteRule 中的内容用作%1

    当一切正常时,您可以将R 更改为R=301

    从不在启用 301 的情况下进行测试,请参阅此答案 Tips for debugging .htaccess rewrite rules 了解详情。

    【讨论】:

    • @mistermartin 它适用于我的测试环境。请清除浏览器缓存。当您插入此规则时,会发生什么或不发生什么?您能在问题中显示您当前的 htaccess 规则吗?
    • 我已经尝试了你的规则的各种组合,甚至只用你的规则删除了我的规则,清除了我的缓存。它为所有内容正确重定向,但 https://www.example.com
    • @mistermartin 这很奇怪,这个规则应该重定向,无论它是否带有https,它在我的测试环境中这样做。
    • 我刚刚在另一台计算机上的另一个浏览器中尝试过,遇到了同样的问题。在我的原始示例中,我已将您的 2 行代码直接放在“RewriteEngine on”之后,而其他一切都保持不变。还有其他想法吗?
    • @mistermartin 不,很遗憾没有,抱歉。
    猜你喜欢
    • 1970-01-01
    • 2015-02-25
    • 2015-04-20
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多