利用nginx实现跨域的两种方法

360 阅读1分钟

前端跨域有多种解决方案,利用nginx有两种方法。

1.配置CORS

location /匹配需要跨域的请求路径 {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

    if ($request_method = 'OPTIONS') {
        return 200;
    }
} 

2.代理转发

location /匹配正常请求路径 {
    proxy_pass http://正常请求目标地址;(一般是本机)
}
location /匹配跨域请求路径 {
    proxy_pass http://跨域请求的目标服务器;(由服务器去跨域请求,客户端就不存在跨域的问题了)
}

写nginx的真他娘的是个人才.jpg。