1. 程式人生 > 其它 >nginx 跨域問題解決

nginx 跨域問題解決

跨域的是一個老生常談的問題,解決方法很多,但是實際使用中大家的方案可能或多或少都會有點問題
以下是自己的一個參考實踐

一般玩法

使用add_header

 
location /  {
set $cors "";
if ($http_origin ~* (\.mydomain\.com|\.myseconddomain\.com)) {
   set $cors "true";
}
proxy_pass http://backend:10005/apathifyouwantso/;
if ($cors = "true") {
 add_header 'Access-Control-Allow-Origin' "$http_origin";
 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
 add_header 'Access-Control-Allow-Credentials' 'true';
 add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
}
}

或者直接使用openresty 的lua 模組

 access_by_lua_block {
                           ngx.header["Access-Control-Allow-Credentials"] = 'true'
                           ngx.header["Access-Control-Allow-Origin"] = '*'
                           ngx.header["Access-Control-Allow-Headers"] = 'Accept,Authorization,authorization,Cache-Control,Content-Type,appkey'
                           local httpmethod = ngx.req.get_method()
                           if httpmethod=="OPTIONS" then
                                  ngx.exit(ngx.HTTP_OK)
                           end           
                         --- 其他lua 處理邏輯
                         ......
 }

以上方案的問題

以上方案有一個問題就是加入我們已經後端的服務同時也新增cors 請求頭,問題就很明顯了,尤其是配置策略不同的時候,很容易造成重複響應請求頭
傳送(然後的問題就很明顯了,cors 失效了。。。。)

比較優的方案

就是對於response 的header 進行重寫,我們可以基於openresty 的header_filter_by_lua 或者使用headers-more-nginx-module
如果需要靈活控制的話,使用lua 模組比較好,如果是靜態的可以直接使用headers-more-nginx-module
headers-more-nginx-module 參考

 
more_set_headers "Access-Control-Allow-Credentials: true";
more_set_headers "Access-Control-Allow-Origin: *";
more_set_headers "Access-Control-Allow-Headers: Accept,Authorization,authorization,Cache-Control,Content-Type,appkey";
access_by_lua_block {
      local httpmethod = ngx.req.get_method()
      if httpmethod=="OPTIONS" then
             ngx.exit(ngx.HTTP_OK)
      end
      --- 其他lua 處理邏輯
       ......
}

說明

基於nginx 解決跨域的方法很多,但是還是需要解決實際調整,同時需要利用好nginx 模組以及openresty 的能力

參考資料

https://github.com/openresty/headers-more-nginx-module
https://github.com/openresty/lua-nginx-module#header_filter_by_lua
http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header