解決nginx跨域問題
阿新 • • 發佈:2018-11-13
導致 options 使用 proc nginx跨域 圖片 type ESS ado 解決nginx跨域問題
1. 無法跨域現象
訪問請求外域URL無法訪問,瀏覽器認為訪問外域URL不安全,導致訪問不了簡稱跨域問題。如下圖:
2. 參數說明
#context配置段: server, location Access-Control-Allow-Origin 註釋:"表示允許訪問的外域URI" Access-Control-Allow-Origin:* 註釋:""*"允許訪問任何外域URL" Access-Control-Allow-Methods 註釋:"首部字段用於預檢請求的響應。其指明了實際請求所允許使用的 HTTP 方法" Access-Control-Allow-Credentials 註釋:"表示是否允許發送Cookie。默認情況下,Cookie不包括在CORS請求之中。設為true,即表示服務器明確許可,Cookie可以包含在請求中,一起發給服務器。這個值也只能設為true,如果服務器不要瀏覽器發送Cookie,刪除該字段即可"
3. Nginx允許跨域配置方法
A 1.允許單域名跨域 add_header ‘Access-Control-Allow-Origin‘ ‘http://ky.test.com‘; add_header ‘Access-Control-Allow-Credentials‘ ‘true‘; add_header ‘Access-Control-Allow-Methods‘ ‘GET,POST,OPTIONS‘; B 2.允許多域名跨域 #nginx跨域配置 #配置段context: http #map指令用來創建變量,僅在變量被接受的時候執行視圖映射操作 map $http_origin $corsHost { #默認值,當沒有設置 default,將會用一個空的字符串作為默認的結果 default 0; "~http://ky.test1.com" http://ky.test1.com; "~https://ky.test1.com" https://ky.test1.com; "~http://ky.dev1.com" http://ky.dev1.com; "~https://ky.dev1.com" https://ky.dev1.com; } #配置段context: server, location add_header ‘Access-Control-Allow-Origin‘ ‘$corsHost‘; add_header ‘Access-Control-Allow-Credentials‘ ‘true‘; add_header ‘Access-Control-Allow-Methods‘ ‘GET,POST,OPTIONS‘; C 3.允許來自任何域的訪問 add_header Access-Control-Allow-Origin ‘*‘;
4. 重載nginx並測試
#重載nginx
nginx -t
nginx -s reload
#跨域測試
見下圖標紅內容 ↓
解決nginx跨域問題