Secure CORS support on Nginx

Cross-Origin Resource Sharing (CORS) is a specification that enables client-side cross-origin HTTP requests. This is particular useful for javascript web applications, since most modern browsers do not allow client-side RPCs to domains other than the origin domain. In short, the server wishing to enable CORS should add the Access-Control-Allow-Origin header to its responses, specifying a list of allowed servers, or the wildcard * to allow cross-origin requests from any domains.

Enable-cors.org provides a list of server configuration files to enable CORS in different servers. However, the configuration file provided for Nginx does not work out of the box for a HTTPS proxy server configuration. Luckily we found an elegant configuration to enable CORS on a HTTPS Nginx Proxy here.

The limitation with the previous solution is that it uses the wildcard *, allowing any website to make cross-origin requests to your server, which raises some security concerns. Unfortunately, the CORS specification only allows a fixed list of URLS to be specified in the Access-Control-Allow-Origin header, preventing the server to allow cross domain requests from a dynamic set of URLs, such as any subdomain of *.mckinsey.com.

In order to overcome this limitation we created a Nginx configuration based on the previous solutions, that enables CORS on a HTTPS Nginx Proxy only to a set of allowed URLs based on a regex. The idea is that the Nginx server will compare the HTTP Origin header with the given regex, and respond with ‘Access-Control-Allow-Origin: $http_origin’ when $http_origin matches the defined regex. For instance, in order to allow CORS requests from any subdomain of *.mckinsey.com, the regex is: /https?://.*\.mckinsey\.com(:[0-9]+)?)$/

The resulting Nginx configuration file is shown in the following gist:

Since the more_set_headers directive is used in the solution, the HttpHeadersMore module must be enabled on the Nginx server. This can be done by recompiling Nginx with that module, or by installing the nginx-extras package, available for Ubuntu and Debian via apt.