Mod_Rewrite漂亮的 URL 中的查询字符串


Mod_Rewrite with Query Strings In Pretty URLs

我有一个 .htaccess 文件,将所有 URL 重定向到带有路由查询字符串参数的索引.php文件:

# Enable Mod_rewrite
RewriteEngine on
# Redirect pretty URLs to the index file
RewriteRule ^(['w'/'-]+)/?$ index.php?route=$1

这很好用,但包含查询字符串的 URL 除外。例如,我有一个表单,该表单重定向回登录屏幕,并带有错误代码(/admin/login?error=1)。显然,问题是,$_GET[error]参数永远不会传递给主脚本。

如何将这些参数传递给脚本?

只需添加 [QSA] 作为标志:

'qsappend|QSA' (查询字符串追加) 此标志强制重写 引擎,用于将替换字符串的查询字符串部分追加到 现有字符串,而不是替换它。当您需要时使用它 通过重写规则向查询字符串添加更多数据。

RewriteRule ^(['w'/'-]+)/?$ index.php?route=$1 [QSA]

这是我

的标准mod_rewrite条目(根据您的问题进行了更改)。我添加它是为了节省任何人使用图像和包含等内容的潜在痛苦。它会重定向除现有文件之外的所有内容。

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(['w'/'-]+)/?$ index.php?route=$1 [QSA]
</IfModule>

设置标志 QSA - 查询字符串追加

# Enable Mod_rewrite
RewriteEngine on
# Redirect pretty URLs to the index file
RewriteRule ^(['w'/'-]+)/?$ index.php?route=$1 [QSA]

(我所做的只是添加[QSA])

Apache Mod_Rewrite文档有更多关于标志的信息。