CORS (Cross-Origin Resource Sharing) source verification failure solution

In web systems, security software scans often find CORS (Cross-Origin Resource Sharing) as a high-risk vulnerability. This article provides a solution using Nginx as a reverse proxy. The solution is to make the following configuration in the nginx.conf file:

  set $cors "";
 if ($http_origin ~* "^http?://.*\.xxxx\.com$") {
      set $cors $http_origin;
 }
 more_set_headers 'Access-Control-Allow-Origin: $cors';
 more_set_headers 'Access-Control-Allow-Credentials: true';
 more_set_headers 'Access-Control-Allow-Methods: GET,POST,OPTIONS';
 more_set_headers 'Access-Control-Allow-Headers: token,Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
 more_set_headers 'Access-Control-Max-Age: 86400';

Notice:

1. "xxxx.com" is a sample domain name, change it according to your actual use. If there are multiple external domain names, process them one by one according to the if method. It is not recommended to use "*" to replace everything.

2. Configuration location 1: before all servers in http, but it may not take effect. If it does not take effect, use configuration position 2.

3. Configuration location 2: Place it before the location part in the server. If there are many servers, they can be placed in a separate file (such as nginx.cors.item) and introduced in the configuration location with the following statement:

#跨域配置
include /usr/local/nginx/conf/nginx.cors.item;

4. Do not configure add_header in the location, otherwise the configuration here will not take effect.

Guess you like

Origin blog.csdn.net/davidwkx/article/details/129078583