允许同站跨域Nginx配置方案
生活随笔
收集整理的這篇文章主要介紹了
允许同站跨域Nginx配置方案
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
基于目前前后端分離的趨勢和微前端解決方案,并且很多web服務部署在Nginx服務器上,那么因為前后端分離導致的跨域問題需要迫切得到解決。因為是否允許跨域的因素有協議、域名、端口,只要有一個不一致就算跨域。大部分需求要求一個一級域名下所有子域名都被允許跨域,一個一個枚舉配置十分繁瑣,且要發版,為了規避這些問題,解決方案如下:
方案一:
map $http_origin $corsHost {default *; # 寫上自己的默認值"~https://csdn.net" https://csdn.net; } server {location / {add_header 'Access-Control-Allow-Origin' $corsHost;...} }方案二(允許所有.csdn.net(:[0-9]+)?結尾origin攜帶cookie跨域)推薦使用
map $http_origin $corsHost {default "";"~\.csdn\.net(:[0-9]+)?$" "$http_origin"; }server {location / {add_header 'Access-Control-Allow-Origin' $corsHost;add_header 'Access-Control-Allow-Credentials' 'true';# 下面兩個屬性可以酌情增減add_header 'Access-Control-Allow-Headers' '*';add_header 'Access-Control-Allow-Methods' '*';} }方案三
location / {set $cors "";if ($http_origin ~* \.csdn\.net(:[0-9]+)?$) {set $cors "true";}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';} }總結
以上是生活随笔為你收集整理的允许同站跨域Nginx配置方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Chrome不显示OPTIONS请求的解
- 下一篇: 【antd】输入控件的思想