Skip to content

Instantly share code, notes, and snippets.

@icepol
Created September 9, 2014 23:37
Show Gist options
  • Save icepol/55f4d0dd8235f47aa4ec to your computer and use it in GitHub Desktop.
Save icepol/55f4d0dd8235f47aa4ec to your computer and use it in GitHub Desktop.
Respond to the OPTIONS request direct from the NGINX.
server {
listen 80;
server_name www.server.name;
location / {
# set default content type here
# add_header may cause double header
types {}
default_type text/html;
# for OPTIONS return these headers and HTTP 200 status
if ($request_method = OPTIONS ) {
add_header Allow "POST, OPTIONS";
add_header Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept";
add_header Access-Control-Allow-Origin "*";
return 200;
}
if (!-f $request_filename) {
proxy_pass http://handler;
break;
}
}
}
@DianaLaa
Copy link

DianaLaa commented Aug 29, 2022

This is exactly what I'm looking for but it does not work. The condition $request_method = OPTIONS does not seem to evaluate to true? The script falls through to the next line and (in my case) forwards the request to my backend. Are there any prerequisites that are not documented here? Is there some setting required before this can be used?

@Rishabh-7
Copy link

Try using $request_method = 'OPTIONS'

@moo2u2
Copy link

moo2u2 commented Sep 15, 2023

It seems that in my case it was caused by my nested location directives. I originally had the check/return under the base location, but it needed to be under the more specific one. Hope this helps anyone else who is doing a similar thing!

location /api/ {
   alias /var/www/mysite
   try_files $uri $uri/ =404
   index index.php
   # Didn't work here

  location ~ \.php$ {
    # Works here
    if($request_method = 'OPTIONS') {
      add_header Content-Length 0;
      return 204;
    }
    fastcgi_pass .....
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment