用你最美的姿態,去「跨域」那座山。 閱讀原文
在平常的開放中,咱們常常遇到跨域的問題,經常使用的處理方式都是在代碼層添加 cors 支持,但若你有 Nginx 配置權限,在 Nginx 上處理跨域將使得程序異常簡單和高效。php
假設咱們的前端域名爲 example.com
,API 服務架設在 api.example.com
域名下,那咱們能夠經過代理的形式來配置跨越請求,具體的配置爲:html
# /etc/nginx/sites-enabled/example.com.conf location /api/ { proxy_pass http://api.example.com/; }
這種方式的原理是將 API 提供的服務,代理到前端域名的二級目錄下,從而避免跨域。前端
固然因爲不少狀況下咱們不想將服務代理到前端域名二級目下,那能夠經過在 Http Response 中添加 Header 來解決跨越,具體配置以下:nginx
# /etc/nginx/snippets/cors.conf; if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always; add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,Content-Disposition' always; add_header 'Access-Control-Max-Age' 1728000 always; add_header 'Content-Length' 0; add_header 'Content-Type' 'text/plain; charset=utf-8'; return 204; } if ($request_method ~* "(GET|POST|DELETE|PUT)") { add_header 'Access-Control-Allow-Origin' '*' always; }
關於什麼時候會發起 OPTIONS 請求及 OPTIONS 請求的內容,可參考阮老師的這篇文章—— 跨域資源共享 CORS 詳解
而後在 API 服務域名下添加 CORS 支持便可api
# /etc/nginx/sites-enabled/api.example.com.conf location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { // 引入 cors 配置 include snippets/cors.conf; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; ... ... }
注意
include snippets/cors.conf
這段代碼的位置,若直接放在 location 中,是不起做用的,以下所示:
location / { include snippets/cors.conf; try_files $uri $uri/ /index.php?$query_string; }
這是由於下面的 try_files
將請求 Forward 到了 location ~ \.php$
這個 block 下,在此以前添加的 add_header
命令是無效的。跨域
enjoy ~_~php7