Home > Net >  nginx does not add my custom header to response
nginx does not add my custom header to response

Time:08-24

I have a rather simple nginx config, which serves a static file as "endpoint". However, the custom header under /version I want to add, is not added.

Can anyone tell me why?

worker_processes  1;

events {
  worker_connections  1024;
}

http {
  map $http_accept $img_suffix {
    "~*webp"  ".webp";
    "~*jxr"   ".jxr";
  }
  server {
    server_tokens off;

    listen 80;
    server_name  localhost;

    root   /usr/share/nginx/html;
    index  index.html index.htm;
    include /etc/nginx/mime.types;

    gzip on;
    gzip_vary on;
    gzip_min_length 1000;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml rss text/javascript;

    location = /version {
      default_type application/json;

      # add test header
      add_header "TEST" "TEST";

      # CORS
      add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Last-Modified";
      if ($request_method = GET) {
        add_header "Access-Control-Allow-Origin"  *;
      }
      if ($request_method = OPTIONS ) {
        add_header "Access-Control-Allow-Origin"  *;
        add_header "Access-Control-Allow-Methods" "GET, OPTIONS, HEAD";
        return 200;
      }

      index version;
    }

    location / {
      # CORS
      if ($request_method ~* "(GET|POST)") {
        add_header "Access-Control-Allow-Origin"  *;
      }

      if ($request_method = OPTIONS ) {
        add_header "Access-Control-Allow-Origin"  *;
        add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
        add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
        return 200;
      }

      add_header Cache-Control 'max-age=31449600'; # one year
      include /etc/nginx/security-headers.conf;
      try_files $uri index.html =404;
    }
  }
}

CodePudding user response:

You cannot have add_header as part of if block. if is part of the rewrite module.

It's an classic example of if is evil

You could probably use map module to set variables and then use them with your add_header directive. There are other options suggested here as well.

How can I add header conditionally in nginx configuration?

  • Related