【问题标题】:How to redirect URLs with a trailing slash to the non-slash variant (with exceptions)?如何将带有斜杠的 URL 重定向到非斜杠变体(有例外)?
【发布时间】:2021-11-22 12:26:03
【问题描述】:

我在设置 NGINX 时遇到了一些问题,以便所有带有斜杠 (/) 的 URL 都永久重定向到不带斜杠的变体。问题是,除了以/backend 开头的 URL 之外,所有 URL 都应该使用该指令。

例如:

https://example.com/service/ --> https://example.com/service
https://example.com/service/one/ --> https://example.com/service/one
https://example.com/backend/ --> https://example.com/backend/ (should not redirect)

我目前正在使用这个指令:

server {
    listen 80;
    listen 443 ssl http2;

    [...]

    location ~ ^/(?!backend)(.+)/$ {
        return 301 $1$is_args$args;
    }

    [...]
}

很遗憾,这里出现以下错误:

https://example.com/service/ --> https://example.com/service/service

有人可以帮我解决这个正则表达式之谜吗?

【问题讨论】:

    标签: regex nginx server webserver


    【解决方案1】:

    您的return 301 $1$is_args$args; 表达式缺少前导/,以便浏览器将重定向解释为相对于当前URI。 service 相对于/service//service/service

    要么捕获$1 中的前导/,要么将其显式添加到return 语句中。

    例如:

    location ~ ^/(?!backend)(.+)/$ {
        return 301 /$1$is_args$args;
    }
    

    【讨论】:

    • 非常感谢!你拯救了我的一天:)!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    相关资源
    最近更新 更多