【问题标题】:Apache rewrite query param to path (url)Apache 将查询参数重写为路径(url)
【发布时间】:2020-08-08 10:51:02
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

  • 你能不能试试这个 - ^(.*/profile)(?:\?)(user=)(\d+)(.*)$ 你可以用这个作为替换文本 - $1/$3$4
  • 我必须在哪里使用它?在没有 RewriteCond 的 RewriteRule 中?
  • RewriteCond 是执行重写规则的条件。如果你想改变你想要的网址,那么它会进入重写规则。
  • 它不工作,调试没有帮助我。
  • 我试图调试我的语法错误(重定向错误太多)。我发现这是因为它正在匹配,但是重定向到/profile/101?user=101,所以它正在匹配另一个时间,等等......

标签: regex apache mod-rewrite


【解决方案1】:

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

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

其中 %2 是 101

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    • 2016-04-05
    • 2016-11-17
    • 2018-10-05
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多