260

nginx add_header 在proxy_pass返回非200时失效

 4 years ago
source link: https://zdb.im/nginx_add_header_proxy_pass_200.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在 nginx 配置里加了一条 add_header 的配置,测试发现在 状态码 400, 401,500 下并不会输出已配置的头,而 200 201 302 状态下却是正常的。

原因是:

add_header 配置只有在 200, 201, 204, 206, 301, 302, 303, 304, or 307 这些状态下才有效。

这是个特殊限制,因为 add_header 在一些错误状态码下会产生意外的作用,比如添加一个 expires 1y 后,会让错误状态意外地缓存超长的时间,导致意外事故。

解决办法:

在 nginx 1.7.5 版本之后,可以给 add_header 的值 添加一个 always 参数,这样就会总是可以输出配置的头部。

比如AJAX跨域请求:

add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Headers Authorization,X-Requested-With,Content-Type,Access-Token always;
add_header Access-Control-Allow-Methods  * always;

这就是出问题的原配置:

location ^~ /v2/ {
    rewrite ^/v2/(.*)$ /$1 break;

    proxy_http_version 1.1;
    proxy_set_header Connection "keep-alive";
    proxy_redirect     off;
    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    proxy_max_temp_file_size 0;
    proxy_connect_timeout      90;
    proxy_send_timeout         3600;
    proxy_read_timeout         3600;
    proxy_buffer_size          4k;
    proxy_buffers              4 32k;
    proxy_busy_buffers_size    64k;
    proxy_temp_file_write_size 64k;

    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Headers X-Requested-With,Content-Type,token;
    add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
    add_header Access-Control-Max-Age 1000;
    add_header Access-Control-Expose-Headers Date;
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Max-Age' 2592000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 200;
    }
    #if (!-f $request_filename) {
            proxy_pass http://swoole9600;
    #}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK