nginx反向代理解決跨域


/usr/local/nginx/conf/nginx.conf

# 代理接口
location ^~ /api/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Headers Origin,X-Requested-Width,Content-Type,Accept;
    proxy_set_header referer "http://shanghaimon.aegis-info.com";
    proxy_set_header host "shanghaimon.aegis-info.com";
    proxy_pass http://shanghaimon.aegis-info.com/api/;
}

location ^~ /qyapi/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Headers Origin,X-Requested-Width,Content-Type,Accept;
    proxy_set_header referer "https://qyapi.weixin.qq.com";
    proxy_set_header host "qyapi.weixin.qq.com";
    proxy_pass https://qyapi.weixin.qq.com/;
}

 

然后刷新配置

/usr/local/nginx/sbin/nginx -s reload

 

 

 

疑難雜症
如果遇到
'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed等等錯誤
contains multiple values "*" 意思就是設置了2次跨域,但是只有一個是允許的。
改動辦法又很多,比如服務器直接允許option請求,服務器就直接可以被跨域訪問了
或者移除其中的任意一個就好了。如果服務器代碼設置了允許跨域,使用Nginx代理里面就不需要了,或者移除服務器中的允許跨域

location ^~ /country/ {
    if ($request_method = 'OPTIONS') {
        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS;
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        return 200;
    }
    proxy_set_header referer "http://114.116.25.112:18116";
    proxy_set_header host "http://114.116.25.112";
    proxy_pass http://114.116.25.112:18116/;
}

 

如果遇到

Access to XMLHttpRequest at 'https://xxxx' from origin 'http://localhost' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

類似於這樣的錯,意思是不允許自定義header頭部信息(比如如上的 加了個token)


nginx放開即可

add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Access-Control-Expose-Headers, Authorization,token';

當然如果你的跨域是程序代碼里做的,你也可以在java代碼中添加

response.addHeader("Access-Control-Expose-Headers", 'token');

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM