DEV Community

Cover image for Quick handle CORS with Nginx
Javid Mougamadou
Javid Mougamadou

Posted on

Quick handle CORS with Nginx

Notes

In some cases, you would like to disable the cross origin requests restrictions because it is only allowed for same origin by default.

In my case, I deal with several APIs with differents origins.

Code

1) GET/OPTIONS endpoint

  location / {
      # Allow some origins
      #if ($http_origin ~* (https?:\/\/(localhost:8000|myfirstorigin:8000))) {
      # set $cors "1";
      #}

      # Allow all origins
      set $cors "1";

      # Append CORS headers to any request from allowed CORS domain, except OPTIONS
      if ($cors = "1") {
          add_header Access-Control-Allow-Credentials true;
          add_header Access-Control-Allow-Origin $http_origin;
      }

      # OPTIONS (pre-flight) request from allowed CORS domain. return response directly
      if ($request_method = 'OPTIONS') {
           add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS, PUT, DELETE';
           add_header Access-Control-Allow-Credentials true;
           add_header Access-Control-Allow-Headers 'Origin,Content-Type,Accept';
           add_header Content-Length 0;
           add_header Content-Type text/plain;
           return 204;
      }

      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_pass https://mysecondorigin/api/;
      proxy_http_version 1.1;
      proxy_read_timeout 600s;
  }
Enter fullscreen mode Exit fullscreen mode

2) POST endpoint

add_header Access-Control-Allow-Origin $http_origin;
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
appsecmonkey profile image
Teo Selenius

Disabling security controls should be done with great care, I highly recommend anyone who considers implementing this configuration to read this first: appsecmonkey.com/blog/cors

Collapse
 
javidjms profile image
Javid Mougamadou

Well explained