Skip to content

Instantly share code, notes, and snippets.

@TheRatG
Last active August 3, 2020 13:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TheRatG/f553c5b19f633699254e57963b6ee6df to your computer and use it in GitHub Desktop.
Save TheRatG/f553c5b19f633699254e57963b6ee6df to your computer and use it in GitHub Desktop.
How to enable Cross-Origin Requests (CORS) on nginx

Open nginx CORS configuration

Wide open nginx CORS configuration CORS is a W3C working standard that currently has decent (but inconsistent) implementions in Firefox, Chrome and Safari. I use it primarily to test PhoneGap apps in regular browsers instead of testing the code in simulators. PhoneGap apps can skip the usual origin checks via configuration, but running a PhoneGap app takes more setup - which make it harder for designers to work with the app. Running apps in simulators or on actual devices also takes al lot more time that just reloading a browser and this annoys me.

Read up on CORS

The nginx configuration

Minimal

location / {
	add_header 'Access-Control-Allow-Origin' '*';
}

Filtered by domain version

location / {
	if ($http_origin ~* (https?://[^/]*\.example\.com(:[0-9]+)?|https?://[^/]*\.otherdomain\.com(:[0-9]+)?)) {
		add_header 'Access-Control-Allow-Origin' "$http_origin";
	}
}

Extended version

location / {
  if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    #
    # Om nom nom cookies
    #
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    #
    # Custom headers and headers various browsers **should** be OK with but aren't
    #
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    #
    # Tell client that this pre-flight info is valid for 20 days
    #
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
    return 204;
  }
  if ($request_method = 'POST') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
  }
  if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
  }
}

Sorces

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