Nginx配置跨域(CORS)


由於瀏覽器同源策略導致Web應用訪問其他站點資源時出現跨域問題。如下圖

簡單說下項目的現狀:

1、服務端,Undertow嵌入式web服務器;

2、前端,通過Nginx托管;

Nginx跨域配置:

1、下載Nginx並安裝。

2、打開Nginx根目錄,config,找到 nginx.cnf 文件新增如下配置:

server {
		listen       80;
		server_name  localhost 127.0.0.1;

		location / {			
			root   c:\root\www\dist;
			index  index.html index.htm;
			# 解決Vue3 history 模式報404問題,Vue2可忽略
			try_files $uri $uri/ /index.html;
		}
		
		location /api {
			add_header 'Access-Control-Allow-Origin' $http_origin;
			add_header 'Access-Control-Allow-Credentials' 'true';
			add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
			add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
			add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
			if ($request_method = 'OPTIONS') {
				add_header 'Access-Control-Max-Age' 1728000;
				add_header 'Content-Type' 'text/plain; charset=utf-8';
				add_header 'Content-Length' 0;
				return 204;
			}
			proxy_pass http://127.0.0.1:8010;
			proxy_set_header Host $host;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header X-Forwarded-Proto $scheme;
			proxy_connect_timeout 5;
		}
	}

特別說明:

(1)/api,表示監聽所有“/api”開頭的請求,比如后台接口:http://example.com/api/news/search?page=1&size=50。

(2)關於端口,80是前台頁面的端口、8010是服務端api端口。

 

3、測試,已經能夠正常返回數據!

 

 

 


免責聲明!

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



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