Quick handle CORS with Nginx

javidjms

Javid Mougamadou

Posted on April 1, 2021

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
💖 💪 🙅 🚩
javidjms
Javid Mougamadou

Posted on April 1, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

What is the Nginx Limit Rate?
webdev What is the Nginx Limit Rate?

September 7, 2024

Quick handle CORS with Nginx
webdev Quick handle CORS with Nginx

April 1, 2021