Nginx跨域处理

Nginx跨域处理一般针对预取请求OPTION作出204响应即可解决。

HTTP OPTION请求

浏览器对所有跨域请求会先执行OPTION请求,服务器返回http状态码200和OK,即认为允许跨域。

Nginx通用跨域方案

针对OPTION请求,返回204解决跨域。

server {
    server_name cs.xieyonghui.com
   
location / {
   add_header 'Access-Control-Allow-Origin' '*';
   add_header 'Access-Control-Allow-Credentials' 'true';
   add_header 'Access-Control-Allow-Methods' '*';
   add_header 'Access-Control-Expose-Headers' '*';
      if ($request_method = 'OPTIONS') {
	   add_header 'Access-Control-Allow-Origin' '*';
       add_header 'Access-Control-Allow-Credentials' 'true';
       add_header 'Access-Control-Allow-Methods' '*';
       add_header 'Access-Control-Expose-Headers' '*';
       add_header 'Access-Control-Allow-Headers' 'Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization,authorization';
       add_header 'Content-Type' 'application/json;charset=UTF-8';
       add_header 'Content-Length' 0;
       return 200;
  	}
	proxy_pass   http://backend/;
}
 listen 80;
}

匹配域名方案

注:以下方案未必有效:

server {
    server_name cs.xieyonghui.com
   
    location / {
        add_header Access-Control-Allow-Origin https://xieyonghui.com;          
    }

    listen 80;
}

通配模式

add_header Access-Control-Allow-Origin *;

匹配https和http

add_header Access-Control-Allow-Origin: http://xieyonghui.com;,https://xieyonghui.com;

add_header Access-Control-Allow-Origin: http://xieyonghui.com;
add_header Access-Control-Allow-Origin: https://xieyonghui.com;

或者

if ($http_origin ~* "^https?://cs\.xieyonghui\.com$" ) {
    add_header Access-Control-Allow-Origin $http_origin;
}