解決nginx已經(jīng)配置過跨域不生效問題
nginx已經(jīng)配置過跨域不生效問題
前端訪問后臺(tái)時(shí)提示跨域
服務(wù)器nginx配置如下
server { listen 80; server_name xxxxxx.com; location / { proxy_pass http://localhost:8061/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,token,platform; add_header Access-Control-Allow-Methods GET,POST,OPTIONS,HEAD,PUT; add_header Access-Control-Allow-Credentials true; proxy_set_header x-real-ip $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; access_log /var/log/nginx/api-access.log; error_log /var/log/nginx/api-error.log; }
很多文章都是說要加上
add_header Access-Control-Allow-Origin *;
但事實(shí)證明我這里已經(jīng)配置了,還是報(bào)跨域,經(jīng)過查詢后發(fā)現(xiàn)關(guān)鍵點(diǎn)在這里
if ( $request_method = 'OPTIONS' ) { return 200; }
最終的配置就是
server { listen 80; server_name xxxxxx.com; location / { proxy_pass http://localhost:8061/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Headers Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,token,platform; add_header Access-Control-Allow-Methods GET,POST,OPTIONS,HEAD,PUT; add_header Access-Control-Allow-Credentials true; proxy_set_header x-real-ip $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; if ( $request_method = 'OPTIONS' ) { return 200; } access_log /var/log/nginx/api-access.log; error_log /var/log/nginx/api-error.log; }
因?yàn)?post 請(qǐng)求 瀏覽器會(huì)發(fā)送一個(gè) options 的預(yù)檢請(qǐng)求,主要將本次的請(qǐng)求頭 發(fā)送給服務(wù)端,若服務(wù)端允許,再發(fā)送真正的post請(qǐng)求,所以 f12 看到,經(jīng)常 post 會(huì)發(fā)送兩次請(qǐng)求。
因?yàn)楹蠖?java 代碼沒有對(duì) options 請(qǐng)求做出處理,導(dǎo)致 options 接口請(qǐng)求的時(shí)候,報(bào) 403 forbidden , 這里 nginx 對(duì) options 的請(qǐng)求直接返回 200,不用到達(dá)接口層,直接允許 post 響應(yīng)頭,即可使得上述失效配置能夠生效
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Nginx利用Lua+Redis實(shí)現(xiàn)動(dòng)態(tài)封禁IP的方法
在站點(diǎn)遇到攻擊且無明顯攻擊特征,造成站點(diǎn)訪問慢,nginx不斷返回502等錯(cuò)誤時(shí),可利用nginx+lua+redis對(duì)該IP進(jìn)行封禁,這篇文章主要給大家介紹了關(guān)于Nginx利用Lua+Redis實(shí)現(xiàn)動(dòng)態(tài)封禁IP的相關(guān)資料,需要的朋友可以參考下2018-12-12Nginx0.5.33+PHP5.2.5(FastCGI)搭建勝過Apache10倍的Web服務(wù)器
Nginx 0.5.31 + PHP 5.2.4(FastCGI)搭建可承受3萬以上并發(fā)連接數(shù),勝過Apache 10倍的Web服務(wù)器的第2版,經(jīng)過了多臺(tái)服務(wù)器的測(cè)試。2009-10-10Nginx服務(wù)器基礎(chǔ)的安全配置與一些安全使用提示
這篇文章主要介紹了Nginx服務(wù)器基礎(chǔ)的安全配置與一些安全使用提示,文中舉了一些典型的Nginx與PHP的環(huán)境用例,需要的朋友可以參考下2016-01-01