Skip to content

Instantly share code, notes, and snippets.

@shreeve
Last active December 19, 2022 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shreeve/bf1cd84414d981bfb9e5d6691254eacc to your computer and use it in GitHub Desktop.
Save shreeve/bf1cd84414d981bfb9e5d6691254eacc to your computer and use it in GitHub Desktop.
Enable CORS in nginx

Configure nginx to handle CORS for us, so we don't even see it

  server {
    server_name _;
    listen      443 ssl http2;
    listen [::]:443 ssl http2;

    root /home/public/www;

    try_files $uri $uri.html $uri/index.html @api;

    location @api {

      # Enable CORS support for all requests
      # Note: This should be able to fail for three reasons:
      # 1) unapproved origin - but, we accept anything
      # 2) unapproved method - but, we accept anything (almost)
      # 3) unapproved header - but, we accept anything
      if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' $http_origin always;
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        add_header 'Access-Control-Allow-Methods' 'GET,HEAD,POST,PUT,PATCH,DELETE';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Max-Age' 86400;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
      }
      # because "If is Evil" in nginx (Google it), we need to repeat two headers here
      add_header 'Access-Control-Allow-Origin' $http_origin always;
      add_header 'Access-Control-Allow-Credentials' 'true' always;
      add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range' always;

      # redirect to our api
      proxy_http_version 1.0; # Unicorn doesn't use keepalive, so don't try
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_redirect off;
      proxy_pass http://api;
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment