How do I set the Access-Control-Allow-Origin header so I can use web-fonts from my subdomain on my main domain?
Notes:
You'll find examples of this and other headers for most HTTP servers in the HTML5BP Server Configs projects https://github.com/h5bp/server-configs
Nginx has to be compiled with http://wiki.nginx.org/NginxHttpHeadersModule (default on Ubuntu and some other Linux distros). Then you can do this
wildcard cors
A more up-to-date answer:
source: https://michielkalkman.com/snippets/nginx-cors-open-configuration.html
You may also wish to add
Access-Control-Expose-Headers
(in the same format as Access-Control-Allow-Headers) in order to expose your custom and/or 'non-simple' headers to ajax requests.-http://www.html5rocks.com/en/tutorials/cors/
Configs for other web servers http://enable-cors.org/server.html
Access-Control-Allow-Credentials
If you're using Access-Control-Allow-Credentials with your CORS request you'll want the cors header wiring within your location to resemble this. As the origin has to match the client domain, wildcard doesn't work.
Here is the article that I wrote which avoids some of the duplication for GET|POST. It should get you going with CORS in Nginx.
nginx access control allow origin
Here is the sample snippet from the post:
In some cases you need to use
add_header
directives withalways
to cover all HTTP response codes.From documentation:
Firstly, let me say that @hellvinz answer is working for me:
However, I have decided to answer this question with a separate answer as I only managed to get this solution working after putting in about ten more hours looking for a solution.
It seems that Nginx doesn't define any (correct) font MIME types by default. By following this tuorial I found I could add the following:
To my
etc/nginx/mime.types
file. As stated, the above solution then worked.Nginx's traditional add_header directive doesn't work with 4xx responses. As we still want to add custom headers to them, we need to install the ngx_headers_more module to be able to use the more_set_headers directive, which also works with 4xx responses.
Then use more_set_headers in the nginx.conf file, i have pasted my sample below
In my case, using Rails 5, the only working solution has been adding the
rack-cors
gem. Like so:in /Gemfile
in config/initializers/cors.rb
source: https://til.hashrocket.com/posts/4d7f12b213-rails-5-api-and-cors
In my case adding the Access Control with a wildcard header didn't work. I ended up having to set the proxy header with my web apps host and Access Control header with the origin set. Here's an example that worked for me: