Created
January 22, 2019 17:35
-
-
Save slavafomin/b1edbdb352a6d9d6909a7f879e4ca7ea to your computer and use it in GitHub Desktop.
How to enable CORS in nginx with origin matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
server { | |
listen 80 default_server; | |
root /var/www; | |
location / { | |
set $cors ''; | |
set $cors_allowed_methods 'OPTIONS, HEAD, GET'; | |
if ($http_origin ~ '^https?://(www\.)?example.com$') { | |
set $cors 'origin_matched'; | |
} | |
# Preflight requests | |
if ($request_method = OPTIONS) { | |
set $cors '${cors} & preflight'; | |
} | |
if ($cors = 'origin_matched') { | |
add_header Access-Control-Allow-Origin $http_origin; | |
add_header Access-Control-Allow-Methods $cors_allowed_methods; | |
} | |
if ($cors = 'origin_matched & preflight') { | |
add_header Access-Control-Allow-Origin $http_origin always; | |
add_header Access-Control-Allow-Methods $cors_allowed_methods; | |
add_header Content-Type text/plain; | |
add_header Content-Length 0; | |
return 204; | |
} | |
} | |
} |
claudiumacovei
commented
Aug 28, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment