Nginx解決跨域問題(CORS)


跨域

解決跨域問題一般有兩種思路:

CORS
在后端服務器設置 HTTP 響應頭,把你需要運行訪問的域名加入加入 Access-Control-Allow-Origin中。

jsonp
把后端根據請求,構造 json 數據,並返回,前端用 jsonp 跨域。

這兩種思路,本文不展開討論。

需要說明的是,nginx 根據第一種思路,也提供了一種解決跨域的解決方案。

環境

centos7
nginx:latest

如何配置

編寫 enable-cors.conf

參考如下

# allow origin list
set $ACAO '*';

# set single origin
if ($http_origin ~* (www.helloworld.com)$) {
  set $ACAO $http_origin;
}

if ($cors = "trueget") {
    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,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}

if ($request_method = 'OPTIONS') {
  set $cors "${cors}options";
}

if ($request_method = 'GET') {
  set $cors "${cors}get";
}

if ($request_method = 'POST') {
  set $cors "${cors}post";
}

引入配置

# ----------------------------------------------------
# 此文件為項目 nginx 配置片段
# 可以直接在 nginx config 中 include(推薦)
# 或者 copy 到現有 nginx 中,自行配置
# www.helloworld.com 域名需配合 dns hosts 進行配置
# 其中,api 開啟了 cors,需配合本目錄下另一份配置文件
# ---------------------------------------------------
server {
  listen       80;
  server_name  *****.com;

  location ~ ^/api/ {
    include enable-cors.conf;   ####關鍵語句
    proxy_pass http://api_server;
    rewrite "^/api/(.*)$" /$1 break;
  }

  location ~ ^/ {
    proxy_pass http://front_server;
  }
}

針對如何解決跨域,方案有很多,本文只是提供了一種思路,方便學習參考
參考文章


免責聲明!

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



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