我的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
我已经达到了对重定向的理解极限。如果你有一个合适的答案,我真的很感谢每一行正在做的事情及其工作原理的演练。当涉及到查询字符串时,对于为什么我现在所拥有的解释不起作用的双重奖励真棒。
答案 0 :(得分:2)
尝试在最后一个重定向规则的末尾添加[QSA]
以保留原始查询字符串,如下所示
# Send to index.php for clean URLs, preserve original query string
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
了解每条线路的作用及其工作原理。
请参阅下面的评论
#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]
答案 1 :(得分:1)
我相信如果你改变这个:
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301]
到此:
RewriteCond %{REQUEST_URI} !^([^?]*)/($|\?)
RewriteRule ^([^?]*) $1/ [L,R=301]
那么它应该做你想做的事。
我所做的改变是:
(.*)
和^(.*)
更改为^([^?]*)
,以确保如果存在查询字符串,则不会将其包括在内正则表达式。 ([^…]
表示“任何不在…
中的字符”,因此[^?]
表示“任何不是问号的字符”。)$
更改为($|\?)
,以便匹配 结束URL 或结束的部分先于所述查询串。$
,因为不再需要它。