首页 > 解决方案 > 多个服务的 NGINX 配置覆盖一个配置的 add_header

问题描述

我无法覆盖特定服务器配置中常规部分中先前添加的标头。

对于对路径及其子路径的“/websocket/.

我的 NGINX 配置中有以下情况,它涵盖了多个服务。

http {
 ...

 add_header              Access-Control-Allow-Origin    *               always;

 server {
  ...
 }
 server {
  ...
 }
 server {
  ...
 }
 server {
  ...
 }
 #this is the new service which needs some special treatment...
 server {
  listen                443 ssl http2;
  server_name           subdomain.domain.com;

  # CORS preflight requests
  if ( $request_method = OPTIONS ) {
    return 204;
  }
  location / {
    set $upstream_servername   servertarget:8081;
    proxy_pass          http://$upstream_servername;
  }

  location /websocket/ {
    set   $upstream_servername   servertarget:8081;
    proxy_pass            http://$upstream_servername;
    proxy_set_header      Access-Control-Allow-Origin https://frontendsubdomain.domain.com;
  }
 }
}

现在我在控制台中收到以下错误

Access to XMLHttpRequest at 'https://subdomain.domain.com/websocket/info' from origin 'https://frontendsubdomain.domain.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://frontendsubdomain.domain.com, *', but only one is allowed.

我不喜欢将 add_header 添加到每个服务,因为它可以是所有其他服务的 *,但对于 websocket,Access-Control-Allow-Origin 必须是请求的 url。

我尝试了一些组合和安排,但没有任何效果,因此只有https://frontendsubdomain.domain.com保留在标题字段中。

这个设置器可以做到这一点,还是我必须使用完全不同的方法?

感谢您的帮助!

标签: nginxnginx-config

解决方案


推荐阅读