如何将其他URL变量添加到已使用mod_rewrite重写的URL中

bil*_*rky 6 .htaccess mod-rewrite get

有没有人知道是否有可能将其他变量放入您正在使用mod_rewrite的URL中,以基本上切入变量.

例如,如果我有URL:

website.com/post/53/post-title/
Run Code Online (Sandbox Code Playgroud)

我正在使用mod_rewrite将其转换为:

website.com/post.php?postid=53
Run Code Online (Sandbox Code Playgroud)

有没有优雅的方法将其他变量放入"预先重写"的URL并保留它们用于我的post.php脚本?

IE,如果我创建如下链接怎么办:

website.com/post/53/post-title/?anothervar=6
Run Code Online (Sandbox Code Playgroud)

到目前为止,似乎我的mod_rewrite代码只是丢弃了额外的变量并将URL发送到post.php脚本,如下所示:

website.com/post.php?postid=53
Run Code Online (Sandbox Code Playgroud)

我知道我可以用它$_SERVER['REQUEST_URI']来获取我的PHP脚本(AKA website.com/post/53/post-title/?anothervar=6)中的原始URL ,然后再由mod_rewrite重写,然后只需将字符串切掉以便在变量上添加,但我只是想知道是否还有更多优雅的解决方案,只使用mod_rewrite.

jan*_*cha 15

您还可以使用%{QUERY_STRING}将原始查询字符串传递给新网址.或者按照您的意愿使用它,例如

RewriteRule /pages/(.*) /page.php?page=$1&%{QUERY_STRING} [R]
Run Code Online (Sandbox Code Playgroud)


And*_*eas 13

http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriterule

"qsappend | QSA"

使用QSA使mod_rewrite在重写时正确"合并"其他参数.

RewriteRule /pages/(.+) /page.php?page=$1 [QSA] 
Run Code Online (Sandbox Code Playgroud)

这将为用户提出的任何请求添加"page = $ 1".

PS.虽然小心,因为mod_rewrite会很高兴地覆盖"页面",尽管用户指定它.我不知道这件事.