在nginx中设置相对路径跳转的方式

671 阅读1分钟

在nginx中的location中,设置301或302的跳转的方式一般是这样的

# 302跳转 
location ~ ^/old/$ {
    return 302 /new/;
}

# 301跳转 
location ~ ^/old/$ {
    return 301 /new/;
}

这里/new/虽然写的是相对路径,但是nginx依然会补齐url的前缀,这样在实际的HTTP请求中会看到Location header中依然是绝对路径的跳转。如果nginx中listen的域名不是最终的域名,这样还可能会造成跳转不成功的问题。

如果需要设置相对路径的跳转,可以考虑以下两种方法。

第一种,设置absolute_redirect off指令,这样就直接关掉了的绝对路径跳转。

# 302跳转
location ~ ^/old/$ {
    absolute_redirect off;
    return 302 "/new/";
}

# 301跳转
location ~ ^/old/$ {
    absolute_redirect off;
    return 302 "/new/";
}

第二种,在跳转的路径前面加一个空格(放在引号里)。

# 302跳转
location ~ ^/old/$ {
    return 302 " /new/";
}

# 301跳转
location ~ ^/old/$ {
    return 301 " /new/";
}

以上这两种方法都可以获得相对路径的跳转。

stackoverflow.com/questions/3…