简体   繁体   English

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

[英]nginx rewrite url and remove last part

Sorry if this question was asked many times. 很抱歉,如果多次询问此问题。 I can't make nginx do proper rewrite. 我不能让nginx做正确的重写。 I need to remove last part of the url. 我需要删除网址的最后一部分。 For example, this is the url I have: 例如,这是我的网址:

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

I need to rewrite these both to this: 我需要重写这两个:

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

This is what I have tried so far: 这是我到目前为止所尝试的:

location / {

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

    ...
}

But it does not work. 但它不起作用。 It seems to me that it is correct? 在我看来,这是正确的吗? What is wrong with that? 这有什么问题? (I hate regex). (我讨厌正则表达式)。

EDIT: 编辑:

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;
}

The 0|1 should be within parentheses or redefined as a character class. 0|1应在括号内或重新定义为字符类。

The rewritten URI needs a leading / as all nginx URIs have a leading / . 重写的URI需要一个前导/因为所有nginx URI都有一个前导/

So all of these should be equivalent: 所以这些都应该是等价的:

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

There's a useful website for regular expressions here . 有正则表达式一个有用的网站在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM