open core »

Nginx and the HTTP OPTIONS method

The current version of Nginx (1.0.x) doesn’t seem to support HTTP OPTIONS requests. It returns 405 "Method Not Allowed" whenever this request is sent.

Here’s an example using curl from the terminal:

$ curl -X OPTIONS busydudes.com

<html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx/1.0.11</center>
</body>
</html>

HTTP OPTIONS requests are essential if you’re doing cross-site HTTP requests and need to obtain the server authorization for the URI where the request originated from.

To solve this problem I found two solutions.

If you’re using another web server behind Nginx and want the request to be handled by that web server, you can trick Nginx into believing that the HTTP status 405 is actually a 200 OK status, so it will just delegate the request to your webserver using the proxy_pass directive. Just keep in mind that this is an ugly fix. Edit your nginx.conf file and add the following:

error_page 405 =200 @405;
location @405 {
    root /;
    proxy_pass http://localhost:8080;
}

Solution 2

If you’re just using Nginx as your main server, or just want to obtain the authorization response for the origin domain, then this is definitely the best solution. Edit your nginx.conf file and add the following:

location / {
    if ($request_method = OPTIONS ) {
        add_header Access-Control-Allow-Origin "http://example.com";
        add_header Access-Control-Allow-Methods "GET, OPTIONS";
        add_header Access-Control-Allow-Headers "Authorization";
        add_header Access-Control-Allow-Credentials "true";
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 200;
    }
}

You should edit the http://example.com to match the origin URI you want to allow. If you want to allow any origin just use the * wildcard.