regex - 使用 htaccess 在 ? 之前强制使用尾部斜线用查询字符串?

标签 regex apache .htaccess routes pattern-matching

我的 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/

相关文章:

apache - 使用 htaccess 将用户从 http 重定向到 https

php - Apache : How to Use Rewrite Engine Inside Alias

PHP session 在子目录中不起作用并终止现有 session

php - Heroku 上 WordPress 的 Http 到 Https 重定向

python - 正则表达式匹配 '#attribute value' 或 'attribute value' 的 linux 配置文件,但不匹配 '# a comment'

python - Regex 模式前的 'r' 是什么意思?

字符串的正则表达式结尾不起作用

java - 在java中使用正则表达式替换 anchor 标记?

apache - 我们真的需要重新启动 IIS 7 应用程序池吗?同样的做法是否适用于其他网络服务器?

apache - htaccess 使用 index.php 重定向到 https