Consider this minimal nginx server configuration

server: {
   listen 80;
   server_name myserver;

   location / {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
        if ($request_method = 'OPTIONS') {
            # Tell client that this pre-flight info is valid for 20 days
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        return 200 my-content;

and the corresponding curl invocations

# this one works as expected
$ curl -v http://myserver
# ...
HTTP/1.1 200 OK
Server: nginx
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, OPTIONS
# ...


# this one is missing the Access-Control-Allow-* Headers
$ curl -v -X OPTIONS http://myserver
# ...
HTTP/1.1 204 No content
Server: nginx
Access-Control-Max-Age: 1728000
Content-Type: text/plain charset=UTF-8
Content-Length 0

So the OPTIONS request is missing the Access-Control-Allow-Origin and Access-Control-Allow-Methods headers, while they are properly set for the GET request. Adding the always Parameter to the add_header directive doesn't work either.

I'm using nginx v1.11.1 on Ubuntu 16.04. Do you have any idea what the problem might be?

  • 4
    You have to copy all add_header directive into if block. nginx.org/r/add_header These directives are inherited from the previous level if and only if there are no add_header directives defined on the current level – Alexey Ten Jul 25 '16 at 12:06
  • BTW, you've missed semicolon in Content-Type header – Alexey Ten Jul 25 '16 at 12:08
  • @AlexeyTen great, thank you, that solved my problem – muffel Jul 25 '16 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.