我已将 nginx 配置为代理端口 8000 的请求,以路由到不同的 IP。在配置中,我还添加了 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;
}
由于标头缺少 Access-Control-Allow-Origin,浏览器阻止对响应执行的任何操作。
浏览器中的错误日志:
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.
答案1
这是预期行为:
句法: 添加标题 名称值[总是];
默认值:— 上下文:http、服务器、位置、如果在位置
当响应代码等于 200、201(1.3.10)、204、206、301、302、303、304、307(1.1.16、1.0.13)或 308(1.13.0)时,将指定字段添加到响应头。该值可以包含变量。
可以有多个指令。当且仅当当前级别上
add_header
没有定义指令时,这些指令才会从上一级继承。add_header
如果
always
指定了该参数(1.7.5),则无论响应代码如何,都会添加标头字段。
你需要总是指令中的关键字add_header
。