How to setup CORS for nginx

How to setup CORS for nginx

Add the following lines into the location block of your server's nginx.conf

  • If you want to serve the content on any site:
add_header Access-Control-Allow-Origin *;
  • If you want to serve the content in some specific sites:
add_header Access-Control-Allow-Origin http://my.site.com;
add_header Access-Control-Allow-Origin https://my.site.com;
add_header Access-Control-Allow-Origin http://my.another.site.com;
  • If you want to match a pattern. For example for any sub-domain of your domain
if ($http_origin ~* "^https?://.*my\.domain\.com$" ) {
    add_header Access-Control-Allow-Origin $http_origin;
}
Buy Me A Coffee