nginx configuration variable interpolation

Maxim Dounin mdounin at mdounin.ru
Mon Mar 27 16:08:37 UTC 2023


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/


More information about the nginx mailing list