【发布时间】:2020-09-27 06:58:03
【问题描述】:
在我的 .htaccess 文件中,我试图实现两件事:-
1) 将任意路径重定向到 /index.php 并将路径作为查询字符串传递,但保留原始 URL
例如example.com/foo/bar 会在后台生成example.com/index.php?foo/bar,但仍会在地址栏中显示example.com/foo/bar 作为URL。
2) 强制 https & www
例如,http://example.com/foo/bar 会在后台生成https://www.example.com/index.php?foo/bar,但会在地址栏中显示https://www.example.com/foo/bar 作为 URL。
以下是我目前所拥有的。
# Redirect to index
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
# When http isn't specified, it redirects to file with same URL
RewriteRule ^(.*)$ index.php?$1 [QSA]
## If no http2
RewriteCond %{HTTPS} off [OR]
## Or if http_host isn't www.
RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
## Then rewrite
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=302]
有了这个,如果https 和www 出现在原始 URL 中,重定向到 index.php 就可以正常工作。这是因为只有第一个规则块被触发,而第二个被跳过。
尽管如果https 或www 不存在,地址栏中的结果URL 是https://www.example.com/index.php?foo/bar 而不是https://www.example.com/foo/bar,因为这两个规则块都被触发了。
我想知道这两个不同的 .htaccess 规则块是否可以组合成一个满足原始要求的块?
谢谢
【问题讨论】:
-
你需要按照相反的顺序做这些事情......首先放置HTTPS重定向,然后内部重写到index.php。
-
@CBroe 说得对。需要维持秩序很重要。为#1 增加了重写规则
标签: .htaccess mod-rewrite