How to add CORS headers to several locations in nginx?

Pablo asked:

I have been able to add a basic CORS support to my nginx server using the code provided in enable-cors.org. However this solution implies to copy and paste that code in every location block, and I have several locations like the following:

location /game1 {
    alias   /development/games/game1/output;
    index  index.html;
}

location /game2 {
    alias   /development/games/game2/output;
    index  index.html;
}

Is there a way to create a rule that includes add_header outside the location blocks?

Edit to clarify: I’ve tried the following

server {
    listen       80;
    server_name  localhost;

    charset UTF-8;

    #access_log  logs/host.access.log  main;

    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        ...
    }
    location /game1 {
        alias /development/games/game1/output;
    }
    ...
}

But it does not work:

2015/10/14 19:00:01 [emerg] 3464#7384: "add_header" directive is not allowed
here in C:developmentserversnginx-1.7.9/conf/nginx.conf:43

My answer:


Sure, you can add add_header under the server block, but then it will always be sent, which might not be what you want.

Otherwise, you can create a file with the directives you want, and then include it from each location where you want the CORS headers added.


View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.