解決nginx跨域問題

解決nginx跨域問題

1. 沒法跨域現象

訪問請求外域URL沒法訪問,瀏覽器認爲訪問外域URL不安全,致使訪問不了簡稱跨域問題。以下圖:

解決nginx跨域問題

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跨域問題

相關文章
相關標籤/搜索