Skip to content

Instantly share code, notes, and snippets.

@dylanninin
Last active April 26, 2018 05:07
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 dylanninin/a23a4bacfefddf4ee824ec0df43fc672 to your computer and use it in GitHub Desktop.
Save dylanninin/a23a4bacfefddf4ee824ec0df43fc672 to your computer and use it in GitHub Desktop.
CORS
# Ansible managed
upstream egolife_backend_api {
server localhost:5000;
}
server {
listen 80;
server_name api.egolife.com;
return 301 https://api.egolife.com$request_uri;
}
server {
listen 443 ssl http2;
server_name api.egolife.com;
ssl_certificate /etc/nginx/ssl/wildcard.egolife.com.cer;
ssl_certificate_key /etc/nginx/ssl/wildcard.egolife.com.key;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
location ^~ /api/ {
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization,DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range' always;
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range,X-Geoip-Country-Code,X-Geoip-Country-Name' always;
add_header 'Access-Control-Max-Age' 86400 always;
add_header X-Geoip-Country-Code $geoip_country_code always;
add_header X-Geoip-Country-Name $geoip_country_name always;
proxy_pass http://egolife_backend_api;
}
}
@dylanninin
Copy link
Author

dylanninin commented Apr 26, 2018

Our usecase

  • Sites: egolife.com/www.egolife.com/hk.egolife.com
  • API: api.egolife.com, provides HTTP + JSON api

Pitfalls

  • add headers to Access-Control-Allow-Headers if request with specified headers, e.g. 'Authorization'
  • add headers to Access-Control-Expose-Headers if specified headers of your response should be exposed to your client
  • set Access-Control-Max-Age to cache your CORS settings
  • add always flag to Nginx's add_header directive to enforce that the header field will be added regardless of the response code.

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