我如何mod_rewrite和保持查询字符串?

Dan*_*key 27 apache .htaccess mod-rewrite query-string

我想mod_rewrite一个URL到另一个页面,但我还希望保留任何添加的查询字符串.

RewriteEngine On

#enforce trailing slashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !#
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://localhost/siteroot/$1/ [L,R=301]

RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1
Run Code Online (Sandbox Code Playgroud)

因此,如果用户访问apps/app1/,index.php?app=app1则显示.但是,我希望能够保留可选的查询字符串,以便访问apps/app1/?variable=x返回index.php?app=app1&variable=x.

什么mod_rewrite规则/条件会使这种情况发生?

Mic*_*ski 55

你需要添加[QSA]标志("查询字符串追加")

RewriteRule ^apps/([A-Za-z0-9-_]+)/?$ index.php&app=$1 [L,QSA]
Run Code Online (Sandbox Code Playgroud)

对于第301页,使用[R]标志重定向而不是像这样的内部重写,将自动追加查询字符串.但是,您必须强制它[QSA]进行内部重写.

  • 澄清一下,这不是重写与重定向有关.http://httpd.apache.org/docs/current/rewrite/flags.html#flag_qsa说:当替换URI包含查询字符串时,RewriteRule的默认行为是丢弃现有的查询字符串,并将其替换为新生成的.使用[QSA]标志会导致组合查询字符串. (2认同)
  • 也许你们已经知道了,但请确保在“QSA”之前不要留空格。这最终会出现 HTTP 500... (2认同)