为什么 add_header 在 nginx 的反向代理配置中不起作用?

为什么 add_header 在 nginx 的反向代理配置中不起作用?

请帮助我理解为什么以下代理配置没有设置标头X-Discourse-Echo-Proxy

server {
  listen 80;
  server_name corsproxy.discourseecho.com;

  error_log /data/nginx/proxy-debug warn;
  # access_log /data/nginx/proxy-access;

  location / {

    proxy_redirect off;
    proxy_set_header Host $arg_proxy_target_domain;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    proxy_cache discourse_corsproxy;
    proxy_cache_valid any 30m;
    proxy_cache_lock on;
    proxy_cache_lock_age 7s;
    proxy_cache_lock_timeout 5s;
    proxy_cache_methods GET HEAD POST;

    proxy_ignore_headers Cache-Control X-Accel-Expires Expires Set-Cookie Vary;
    proxy_hide_header Set-Cookie;
    proxy_hide_header Cache-Control;
    proxy_hide_header Expires;
    proxy_hide_header X-Accel-Expires;
    proxy_hide_header Vary;
    proxy_hide_header Access-Control-Allow-Origin;
    proxy_hide_header Access-Control-Allow-Credentials;

    add_header X-Cache-Status $upstream_cache_status always;
    add_header X-Discourse-Echo-Proxy "1" always;

    # Nginx doesn't support nested If statements, so we
    # concatenate compound conditions on the $cors variable
    # and process later
   # If request comes from allowed subdomain
    # (discourseecho.com) then we enable CORS
    if ($http_origin ~* (https?://discourseecho\.com$)) {
       set $cors "1";
    }

    # If request comes from my home IP (Adelaide), enable CORS
    if ($remote_addr = "103.192.193.144") {
      set $cors "1";
    }

    # OPTIONS indicates a CORS pre-flight request
    if ($request_method = 'OPTIONS') {
       set $cors "${cors}o";
    }

    # Append CORS headers to any request from
    # allowed CORS domain, except OPTIONS
    if ($cors = "1") {
       add_header Access-Control-Allow-Origin $http_origin always;
       add_header Access-Control-Allow-Credentials "true" always;
       proxy_pass $arg_proxy_target_protocol://$arg_proxy_target_domain;
    }
   # OPTIONS (pre-flight) request from allowed
    # CORS domain. return response directly
    if ($cors = "1o") {
       add_header Access-Control-Allow-Origin $http_origin' always;
       add_header Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE" always;
       add_header Access-Control-Allow-Credentials "true" always;
       add_header Access-Control-Allow-Headers "Origin,Content-Type,Accept" always;
       add_header Content-Length 0;
       add_header Content-Type text/plain;
       return 204;
    }

    # Requests from non-allowed CORS domains
    proxy_pass $arg_proxy_target_protocol://$arg_proxy_target_domain;
  }
}

我期望根据以下指令添加标题:

add_header X-Discourse-Echo-Proxy "1" always;

但无论我发出什么 HTTP 请求,响应中都没有这样的标头。日志文件中没有错误或警告。我应该检查什么来识别问题?

答案1

我觉得 if 语句可能会破坏封闭块中的 add_header 指令。文档中写道:“可能存在多个 add_header 指令。这些指令继承自上一级当且仅当当前级别上没有定义 add_header 指令。”这意味着你可能必须在 if 块内重复自己。

相关内容