Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active August 9, 2019 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelmota/e6ff72c7d139896f25bd91dcc826b55e to your computer and use it in GitHub Desktop.
Save miguelmota/e6ff72c7d139896f25bd91dcc826b55e to your computer and use it in GitHub Desktop.
Nginx cors
The cors headers in nginx.conf fixes the errors:
# firefox
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/. (Reason: CORS request did not succeed)
# safari
Failed to load resource: Origin http://example.com/ is not allowed by Access-Control-Allow-Origin.
Fetch API cannot load https:/remote.example.com. Origin http://example.com/ is not allowed by Access-Control-Allow-Origin.
server {
listen 80;
server_name example.com;
location / {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE,PATCH';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_pass https://upstream_server/;
more_clear_headers 'Access-Control-Allow-Origin';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment