【问题标题】:Rewrite regexp in nginx在nginx中重写正则表达式
【发布时间】:2021-05-30 19:17:55
【问题描述】:

这是 nginx 配置:

location @rewrite {
    rewrite ^/threads/ /thread.php?$uri&$args last;
}

该代码运行良好,但我现在想使用另一条路线。

OLD: /threads/123-yyy-yyy-yyy
NEW: /xxx-xxx-xxx/123-yyy-yyy-yyy

我尝试过一些类似的方法:

rewrite ^\/[\w]+\/([\d]+-[\w]+)?$ /thread.php?$1&$args last;
rewrite ^/[\w]+/([\d]+-[\w]+)?$ /thread.php?$1&$args last;
rewrite ^/\w+/(\d+-\w+)?$ /thread.php?$1&$args last;
rewrite ^/\w+/(\d+-\w+)$ /thread.php?$1&$args last;

但是找不到页面,所以我猜我的正则表达式有问题。 可能是 $uri/$1 参数吗?

【问题讨论】:

    标签: regex nginx url-rewriting


    【解决方案1】:
    1. 您不需要将&$args 添加到您的重写规则中。作为 nginx rewrite 文档states

    如果 replacement 字符串包含新的请求参数,则之前的请求参数会附加在它们之后。如果这是不希望的,在替换字符串的末尾放置一个问号可以避免附加它们,例如:

    rewrite ^/users/(.*)$ /show?user=$1? last;
    
    1. \w 元字符包括a-zA-Z0-9 和下划线(_)。它不包括破折号字符。你可以试试这个正则表达式:

      rewrite ^\/[-\w]+\/([\d]+-[-\w]+)$ /thread.php?$1 last;
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2020-08-15
      • 1970-01-01
      相关资源
      最近更新 更多