【问题标题】:Nginx 301 redirect with round brackets in URLNginx 301 在 URL 中使用圆括号重定向
【发布时间】:2012-10-20 02:37:54
【问题描述】:

当相关 URL 带有圆括号时,我很难在 nginx 中进行基本的 301 重定向。

通常,我会简单地使用这种类型的基本定位规则(不带括号):

location /abc/def {
rewrite /abc/def http://new.domain.com/abc/def/ permanent;
}

在上面提到的 URL 有圆括号的情况下:

来源网址:domain1.com/abc/def(ghi) 目标网址:domain2.com/abc/defghi

location /abc/def(ghi) {
rewrite /abc/def(ghi) http://new.domain2.com/abc/defghi permanent;
}

不幸的是,它不像第一个示例那么简单。从那以后,我已经多次更改规则以包括转义、用于打开和关闭圆括号的 urlencoded、正则表达式以允许在括号中捕获单个字符,但似乎没有任何效果。

转义方式:

location /abc/def\(ghi\)

当 URL 有括号时,如何获得 301 重定向以在 nginx 中工作?

【问题讨论】:

    标签: redirect nginx rewrite


    【解决方案1】:
    location /abc/def(ghi) {
        return 301 http://new.domain2.com/abc/defghi;
    }
    

    【讨论】:

    • 感谢一百万个惊人的快速响应和解决方案!
    【解决方案2】:

    虽然在这种特定情况下,VBart 的回答有效,但它不是一个通用的解决方法。

    基本问题是() 是正则表达式中的特殊字符, 解决这个问题的一般方法是避开那些特殊字符 但是问题是,只有在 " 中包含正则表达式时,使用 \ 转义才有效

    像这样:

    location /abc/def(ghi) {
      rewrite "/abc/def\(ghi\)" http://new.domain2.com/abc/defghi permanent;
    }
    

    【讨论】:

    • 只有在 " 中包含正则表达式时才有效 不,你错了。仅当正则表达式包含 {; 章程时,才应将其括在引号中。请参阅文档:nginx.org/r/rewrite
    • 问题是作者将\ 放在() 前缀location 之前(不是正则表达式之一)。 nginx.org/r/location
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 2016-10-24
    • 2018-08-14
    • 2015-08-11
    • 2016-10-17
    • 2016-08-28
    相关资源
    最近更新 更多