大网数据广告活动
服务器运维问答

Change upstream response from 302 to 301 in nginx

· 52CE 我爱测

I have a Django app as an upstream using Gunicorn in nginx, and that app sometimes sent me back a 302 with a Location. And that it's perfectly fine. We can't touch Django's code but colleagues need the 302 to be 301. So I would l…

问题原文

原帖链接 · Paolo · CC BY-SA 4.0

I have a Django app as an upstream using Gunicorn in nginx, and that app sometimes sent me back a 302 with a Location. And that it's perfectly fine.

We can't touch Django's code but colleagues need the 302 to be 301.

So I would like to modify that 302 to 301, but I haven't found a way to do it without using LUA. I have tried combinations of "error_page" statement, eg. error_page 302 =301 @redirect; with the "proxy_intercept_errors on;", named location, etc. but haven't had any luck.

Is there any quick way to achieve it? Thanks.

Edit1: Here below my pretty simple upstream:

upstream test {
  server unix:/webapps/test/gunicorn.sock fail_timeout=0;
}

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

You can change the 3xx status code by using proxy_intercept_errors and error_page as you suggest.

You will need to use the value from $upstream_http_location to reconstruct the Location header in the replacement response.

In its simplest form, you could use:

proxy_intercept_errors on;
error_page 302 = @redirect;
location @redirect {
    return 301 $upstream_http_location;
}

In this case, $upstream_http_location is the original value for the Location header in the response from the upstream server before being transformed by proxy_redirect - equivalent to using proxy_redirect off;.

This may be sufficient for your needs.


However, if you need to rewrite the Location response header - for example, if you are using proxy_redirect default; - you may need to modify the response using a map.

For example:

map $upstream_http_location $location {
        ~^https?://[^/]+(.*)$    $1;
        default                  /oops;
}

server {
    ...
    proxy_intercept_errors on;
    error_page 302 = @redirect;
    location @redirect {
        return 301 $location;
    }
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2022-11-09)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。