我的 htaccess 文件中有以下内容:
RewriteEngine On
RewriteBase /
# Check to see if the URL points to a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Trailing slash check
RewriteCond %{REQUEST_URI} !(.*)/$
# Add slash if missing & redirect
RewriteRule ^(.*)$ $1/ [L,R=301]
# Check to see if the URL points to a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Send to index.php for clean URLs
RewriteRule ^(.*)$ index.php?/$1 [L]
这确实有效。它隐藏了 index.php,并添加了一个尾部斜线……除非有查询字符串。
这个网址:
http://example.com/some-page
被重定向到:
http://example.com/some-page/
但是这个网址:
http://example.com/some-page?some-var=foo&some-other-var=bar
不会被重定向。我希望将以上内容发送至:
http://example.com/some-page/?some-var=foo&some-other-var=bar
我已经达到了我对重定向的理解的极限。如果您有一个有效的答案,我将非常感谢您逐步了解每条线的作用及其工作原理。双重奖励,解释为什么当涉及查询字符串时我现在拥有的东西不起作用。
最佳答案
尝试在最后一个重定向规则的末尾添加一个 [QSA]
以保留原始查询字符串,如下所示
# Send to index.php for clean URLs, preserve original query string
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
a walkthrough of what every line is doing and why it works.
请看下面我的评论
#turn mod_rewrite engine on.
RewriteEngine On
#set the base for urls here to /
RewriteBase /
### if the is not a request for an existing file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
### and the URI does not end with a /
RewriteCond %{REQUEST_URI} !(.*)/$
### redirect and add the slash.
RewriteRule ^(.*)$ $1/ [L,R=301]
### if the is not a request for an existing file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# rewrite to index.php passing the URI as a path, QSA will preserve the existing query string
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
关于regex - 使用 htaccess 在 ? 之前强制使用尾部斜线用查询字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9117130/