nginx重写url并删除最后一部分

时间:2017-12-12 12:08:28

标签: nginx url-rewriting

很抱歉,如果多次询问此问题。我不能让nginx做正确的重写。我需要删除网址的最后一部分。例如,这是我的网址:

https:/mydomain.com/this/is/some/url/page/0
https:/mydomain.com/this/is/some/url/page/1

我需要重写这两个:

https:/mydomain.com/this/is/some/url

这是我到目前为止所尝试的:

location / {

    ...
    rewrite ^/(.*)/page/0|1$ $1 last;

    ...
}

但它不起作用。在我看来,这是正确的吗?这有什么问题? (我讨厌正则表达式。)

修改

location / {
    # Remove trailing double slashes.
    if ($request_uri ~ "^[^?]*?//") {
        rewrite "^" $scheme://$host$uri permanent;
    }
    # Remove trailing slashes.
    rewrite ^/(.*)/$ /$1 permanent; 

    # Rewrite page/0 and page/1 from url.
    rewrite ^/(.*)/page/[01]$ /$1 last;

    proxy_pass                      http://backend_web;
    proxy_set_header                Host $host;
    proxy_set_header                X-Real-IP $remote_addr;
}

1 个答案:

答案 0 :(得分:2)

0|1应在括号内或重新定义为字符类。

重写的URI需要前导/,因为所有nginx URI都有前导/

所以这些都应该是等价的:

rewrite ^/(.*)/page/(0|1)$ /$1 last;
rewrite ^/(.*)/page/[01]$ /$1 last;
rewrite ^(/.*)/page/[01]$ $1 last;

有一个有用的正则表达式网站here

相关问题