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

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

最佳答案

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

重写的 URI 需要一个前导 /一样nginx URI 有一个领先的 / .

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

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

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

关于nginx 重写 url 并删除最后一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772291/

相关文章:

java - 使用 JSF/PrettyFaces 获取当前页面名称

logging - 使用 nginx 记录已解析的请求

.htaccess - htaccess RewriteRule 带有文字问号(不是查询字符串)

ruby-on-rails - 上游在读取来自上游的响应 header 时使用 Nginx、Thin/Rails 超时

ruby-on-rails - 未找到 Nginx + Rails 4 Assets

wordpress - 如何在本地成功使用 browser-sync with wordpress?

php - php 和 mysql 中动态网站的搜索引擎优化/内容列表/url 重写

python - 如何围绕第三方 servlet 包装 Plone 身份验证?

nginx - 如何使用 nginx 启用 xdebug?

apache - .htaccess 重写规则不会使用 unicode 字符