Why do I have to return the response code for cors preflight requests on my in nginx?

26 views Asked by At

I spent some time to configure nginx to handle cors requests for a media folder of a web application. I saw a lot of articles and issue responses which tell to handle the OPTIONS request and return a successful response code. But I haven't understand why this is necessary. This is my solutions I came up with:

# /etc/nginx/conf.d/default.conf

# Determine if it's a valid origin and set it in the $cors variable.
map "$http_origin" $cors_origin {
  default '';
  "~^https?://example1.com?$" "$http_origin";
  "~^https?://example2.com?$" "$http_origin";
}

server {
    listen       80;
    server_name  localhost;

    location /data {

      add_header 'Access-Control-Allow-Origin' "$cors_origin";
      add_header 'Access-Control-Allow-Headers' '*';

      if ($request_method = 'OPTIONS') {
        return 204;
      }
    }

Everything works fine and like I expect. Without this part

if ($request_method = 'OPTIONS') {
        return 204;
}

nginx returns responses with 405. And I don't exactly understand why it is needed. On the examples on the internet I can't find an explanation for it. Maybe someone can help me understand it.

Thanks!

0

There are 0 answers