nginx configuration variable interpolation

Vilius Šumskas vilius.sumskas at rivile.lt
Tue Mar 28 05:50:55 UTC 2023


Thank you for your response.
I've made a mistake. I've made my initial tests with a lot of different combinations and last value I have used, which doesn't add header at all, is indeed an empty string, not 0. So it seems this works as expected.

I think it is functionality worth documenting though. When I searched the internet for "how to add nginx header conditionally" there was dozen of examples which used only ifs, or a combination of maps and ifs, but none of them actually mentioned that add_header is on itself conditional.

-- 
   Best Regards,
    Vilius

-----Original Message-----
From: nginx <nginx-bounces at nginx.org> On Behalf Of Maxim Dounin
Sent: Monday, March 27, 2023 7:09 PM
To: nginx at nginx.org
Subject: Re: nginx configuration variable interpolation

Hello!

On Mon, Mar 27, 2023 at 03:24:06PM +0000, Vilius Šumskas wrote:

> I have the following directive in Nginx configuration:
> 
> location /docs {
>     add_header Access-Control-Allow-Origin $cors_origin; }
> 
> $cors_origin comes from the map {} where the value is set to * or something else.
> 
> I have noticed that if $cors_origin is set to 0, add_header doesn’t 
> add Access-Control-Allow-Origin header at all. Is this expected? I 
> don’t see anything about such behaviour in the add_header 
> documentation.

The header will not be added if the value is an empty string.  If it is not empty but "0", the header will be added just fine.  For example, consider the following configuration:

map $uri $cors_origin {
    default 0;
}

server {
   ...
   location / {
      add_header Access-Control-Allow-Origin $cors_origin;
      return 204;
   }
}

Test:

$ telnet 127.0.0.1 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.0

HTTP/1.1 204 No Content
Server: nginx/1.22.1
Date: Mon, 27 Mar 2023 16:01:05 GMT
Connection: close
Access-Control-Allow-Origin: 0

Connection closed by foreign host.


As you can see from the telnet output, the Access-Control-Allow-Origin is properly added.  If you are seeing a different behaviour, you may want to recheck the value actually being used.  If it is indeed "0", and not an empty string, please provide more details.

-- 
Maxim Dounin
http://mdounin.ru/
_______________________________________________
nginx mailing list
nginx at nginx.org
https://mailman.nginx.org/mailman/listinfo/nginx


More information about the nginx mailing list