首页 > 解决方案 > Apache 将查询参数重写为路径(url)

问题描述

我有一个应用程序,它有一个类似的页面my-site.com/profile?user=<userIdHere>,我改变了处理路由的方式,以便获得一个干净的 url my-site.com/profile/<userIdHere>。例如,我想创建一个从/profile?user=101to的重定向/profile/101

我没有找到任何这样的例子,我无法让它工作。我当时做了什么:

        RewriteCond %{QUERY_STRING} ^user=(.*?)
        RewriteRule ^/profile /profile/%1 [R=301,NC,L]

但我收到“重定向过多”错误。我会做的另一件事:有时我还有其他查询参数,例如:/profile?user=101&anotherParam=test. 如何保留其他查询参数?

谢谢

标签: regexapachemod-rewrite

解决方案


多亏了这篇文章,我终于做到了,只需删除我的条件匹配的查询参数(以防止过多的重定向),并将其值注入路径中:

        RewriteCond %{QUERY_STRING} ^(.*)?&?user=([^&]+)&?(.*)?
        RewriteRule ^/profile$ /profile/%2?%1%3 [R=301,NC,L]

其中 %2 是101


推荐阅读