Nginx的反向代理问题为4xx响应代码

我已经configurationnginx代理到端口8000的请求,路由到不同的IP。 在configuration中,我还添加了Access-control-Allow-Origin头。 如果服务器响应2xx响应代码,这工作正常。 但是,如果服务器响应4xx响应代码,它不包括下面提到的头

server { listen *:8000; ssl on; ssl_certificate /etc/nginx/ssl/axis.crt; ssl_certificate_key /etc/nginx/ssl/axisPrivate.key; server_name website.com; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP; access_log /var/log/nginx/nginx.vhost.access.log; error_log /var/log/nginx/nginx.vhost.error.log; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_pass https://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_redirect off; proxy_intercept_errors off; # Simple requests if ($request_method ~* "(GET|POST|PUT)") { add_header "Access-Control-Allow-Origin" "https://website.com"; } # Preflighted requests if ($request_method = OPTIONS ) { add_header "Access-Control-Allow-Origin" "https://website.com"; add_header "Access-Control-Allow-Methods" "GET,PUT,POST, OPTIONS, HEAD"; add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept,access-control-allow-methods,access-control-allow-origin"; return 200; } } } upstream api { server ip:port; } 

由于标题缺lessAccess-Control-Allow-Origin,因此浏览器将阻止对响应执行的任何操作。

错误login浏览器:

 POST https://website.com:8000/employee 409 () EmployeeRegistration:1 Failed to load https://website.com:8000/employee: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://website.com' is therefore not allowed access. The response had HTTP status code 409. 

这是预期的行为 :

语法: add_header 名称值 [always];

默认: – 上下文:http,服务器,位置,如果在位置

如果响应代码等于200,201(1.3.10),204,206,301,302,303,304,307(1.1.16,1.0.13)或308(1.13),则将指定的字段添加到响应报头.0)。 该值可以包含variables。

可能有几个add_header指令。 当且仅当在当前级别上没有定义add_header指令时,这些指令才从上一级inheritance。

如果指定了always参数(1.7.5),则无论响应代码如何,标题字段都将被添加。

您需要add_header指令中的always关键字。