foreword
CORS (Cross-Origin Resource Sharing) Cross-origin resource sharing is a mechanism that allows resources (such as html/js/web service) of the current domain (such as html/js/web service) to be accessed by scripts in other domains (domain), usually due to the same domain. The same-origin security policy browser prohibits such cross-origin requests.
For example, when a.com requests resources from b.com, it involves cross-domain. At present, common cross-domain solutions are generally divided into the following categories:
- jsonp return value to solve get request
- iframe solves cross-domain access
- Nginx solves CORS
Nginx configuration
1 Simple configuration
server {
listen 80;
server_name b.com;
location /{ add_header 'Access-Control-Allow-Origin' 'http://a.com'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET'; } }
-
add_header: Authorize requests from a.com
-
The second add_header: When this flag is true, whether it can be exposed in response to the request
-
The third add_header: Specify the method of the request, which can be GET, POST, PUT, DELETE, HEAD
also supports wildcards, such as allowing requests from any domain:
server {
listen 80;
server_name b.com;
location /{
Access-Control-Allow-Origin: *
}
}
2 Advanced configuration
location / {
if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # # Custom headers and headers various browsers *should* be OK with but aren't # add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type'; # # Tell client that this pre-flight info is valid for 20 days # 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-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-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'; } }
Because POST cross-domain requests will first send an OPTIONS sniffing request, all scenarios involve setting OPTIONS.