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

How can I replace Access-Control-Allow-Origin header in proxy response with nginx

· 52CE 我爱测

I am using a simple nginx instance to proxy REST calls to another server. The purpose of my proxy is to allow the use of cookies for authentication. I have it working, except for one problem. The server providing the REST service…

问题原文

原帖链接 · Michael Taylor · CC BY-SA 3.0

I am using a simple nginx instance to proxy REST calls to another server. The purpose of my proxy is to allow the use of cookies for authentication. I have it working, except for one problem. The server providing the REST service is sending the header Access-Control-Allow-Origin *. That header is too permissive for cookie based authentication. I need to replace that header with one that is more restrictive.

Here is a subset of my nginx config:

map $http_origin $cors_header {
    default "";
    "~^https?://[^/]+\.mydomain\.com(:[0-9]+)?$" $http_origin;
}

server {    
    location / {
        proxy_pass https://myrestserver.com/api;
        add_header Access-Control-Allow-Origin $cors_header;
        add_header Access-Control-Allow-Credentials true;
    }
}

My problem is that I end up with two Access-Control-Allow-Origin headers present in my response. How can I replace the header that comes back from the REST server so that only my version of the header is present in the final response?

已采纳解答

原帖链接 · suitablyawesome · CC BY-SA 3.0

The best thing to do would be to change the response on the REST server side, but, assuming you don't have control of the REST server, there is a module for Nginx that can modify headers called ngx_headers_more: https://github.com/openresty/headers-more-nginx-module

You'll have to install the module (this will likely involve building nginx from source and adding the module in ./configure, as described in the github readme). For your specific problem, once you install it you can add this directive in any block

more_set_headers "Access-Control-Allow-Origin: $cors_header"

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

资料来源与适用范围

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

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

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