首页 > 解决方案 > 从 http 重定向到 https 时 mod_rewrite 中的无限重定向

问题描述

.htaccess 文件如下所示,可以很好地将流量从 website.com/page 或 website.com/page/ 重定向到 index.php?site=page,从 website.com/page/subpage/ 重定向到 index.php ?site=page&sub=子页面。

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]

RewriteRule ^([^/]+)$ index.php?site=$1 [QSA]
RewriteRule ^([^/]+)/$ index.php?site=$1 [QSA]
RewriteRule ^([^/]+)/([^/]+)/$ index.php?site=$1&sub=$2 [QSA]

尝试将流量从 http:// 重定向到 https:// 时出现问题

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/$1 [R,L]

我收到一条消息,指出网站上的重定向太多,无论 url 是什么。你知道出了什么问题吗?

标签: regex.htaccesshttpmod-rewrite

解决方案


你的规则应该是这样的:

RewriteEngine On

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

RewriteRule ^([^/.]+)/?$ index.php?site=$1 [QSA,L]
RewriteRule ^([^/.]+)/([^/.]+)/?$ index.php?site=$1&sub=$2 [QSA,L]

确保在新浏览器中进行测试以避免旧浏览器缓存。


推荐阅读