Last Updated: February 25, 2016
· elcuervo

Nginx CORS configuration

I've found some situations (specially API design) when it becomes really useful to allow other hosts to do cross site ajax request.

Normal ajax request (same site) executes it when you call it, but cross site ajax requests executes an OPTIONS first and checks for some given headers.

The Access-Control-Allow-Origin checks from where the server allows requests, using an * allows you to let everyone pass.

This is how you enable it using Nginx:

location / {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'POST, GET, OPTIONS';
        add_header 'Access-Control-Max-Age' '1728000';
        add_header 'Content-Type' 'text/plain; charset=UTF-8';
        return 200;