Nginx how enable CORS for multi origins ?
submitted a month ago by Rick_C137
cross-posted from: https://programming.dev/post/18360806
Hi everyone,
I would like to enable Cross-Origin Resource Sharing on my Nginx server. for few origins (cors requestor)/domains.
I've found this article https://www.juannicolas.eu/how-to-set-up-nginx-cors-multiple-origins that is nice, but not complete and on my browser seem really hard to read due to the layout 🤮
So I've opened a CodeBerg git repository for the good soul that want to perfect this piece of code the allow the most of use to use CORS with Nginx.
https://codeberg.org/R1ckSanchez_C137/BestOfxxx/src/branch/main/Nginx/CORS_MultiDomains.py
If you don't want to create an account on codeberg feel free to post your code here !
server { # Server map "$http_origin" $cors { # map in Nginx is somewhat like a switch case in a programming language. default ''; #Seem to set $cors to '' empty string if none of the follwing rexeg match ? "~^https:\/\/([\w-_\.]+\.)?example.com$" "$http_origin"; #regex domain match # ~ mean I suppose the string is RegEx ? # Need to come with a RegEx expression that match https://anything.example.com[optional ports and Query string ?X=Y] "~^https:\/\/([\w-_\.]+\.)?example2.com$" "$http_origin"; #regex domain match } location /static { # if preflight request, we will cache it if ($request_method = 'OPTIONS') { add_header 'Access-Control-Max-Age' 1728000; #20 days add_header 'Content-Type' 'text/plain charset=UTF-8'; add_header 'Content-Length' 0; return 204; #https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204 } if ($cors != "") { add_header 'Access-Control-Allow-Origin' "$cors" always; # <-- Variable $cors add_header 'Access-Control-Allow-Credentials' 'true' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always; add_header 'Access-Control-Allow-Headers' 'Accept, Authorization, Cache-Control, Content-Type, DNT, If-Modified-Since, Keep-Alive, Origin, User-Agent, X-Requested-With' always;} # configuration lines... } } }
You either allow a single origin, or allow them all with "*".