Those who often read this blog already know that we're deeply in love with NGINX, a lightweight, high-performance and open-source web server and reverse proxy used by more than 358 million websites and over 66% of the world’s top 10,000 websites. And no, we're not taking money from them to say this, we just happen to like it a lot.
Anyway, in this post I'll briefly share the CORS configuration I'm using for the web sites that need to perform Cross Request Resource Sharing activities of any kind - such as using web-fonts from a subdomain on a main domain, or something like that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
location / { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; } } |
Since it's a pretty long piece of code, you might want to put this on a separate file (such as /etc/nginx/cors-settings.conf ) and then include it with the following one-liner:
1 |
include /etc/nginx/cors-settings.conf; |
Pretty neat, isn't it?
If you're looking for further info about how to set & configure other NGINX security headers, such as X-Frame-Options, HTTP Strict Transport Security (HSTS), X-XSS-Protection, X-Content-Type-Options, Content Security Policy and Referrer Policy, be sure to check our NGINX HTTP Security Headers guide.
Job for nginx.service failed because the control process exited with error code.
See “systemctl status nginx.service” and “journalctl -xe” for details.