Ajax 跨域请求 Access-Control-Allow-Origin 问题小记

匿名 (未验证) 提交于 2019-12-03 00:32:02

前言

在前后端分离的项目中经常会遇到 Ajax 跨域的问题,然而网上大多数教程都是使用 * 通配符放行所有请求。然而这是不对的,没有解决根本问题。

正文

其实放行指定的域名很简单,下面我介绍下 PHP 和 Nginx 的。

PHP

$http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : ''; if (preg_match('/domain1.com|domain2.com$/i', $http_origin)) {     header('Access-Control-Allow-Origin: ' . $http_origin);  }
PHP

Nginx

location / {     if ($http_origin ~ 'domain1.com|domain2.com$') {         add_header Access-Control-Allow-Origin $http_origin;     } }
NGINX

Access-Control-Allow-Origin

是不是很简单,直接在代码中使用正则进行匹配。只要你会正则,更严格的匹配模式自然就会了。

下面附上其他模式:

放行所有域名

PHP

header('Access-Control-Allow-Origin: *');
PHP

Nginx

add_header Access-Control-Allow-Origin *;
NGINX

放行单个域名

PHP

header('Access-Control-Allow-Origin: http://domain1.com');
PHP

Nginx

add_header Access-Control-Allow-Origin http://domain1.com;
NGINX

求知

看到这里肯定肯定有人会疑问,为什么放行多个域名不这样写:

header('Access-Control-Allow-Origin: http://domain1.com'); header('Access-Control-Allow-Origin: http://domain2.com');
PHP
add_header Access-Control-Allow-Origin http://domain1.com; add_header Access-Control-Allow-Origin http://domain2.com;
NGINX

首先,PHP 这样写没问题,Nginx 这样写会提示:

XMLHttpRequest cannot load http://domain2.com. The 'Access-Control-Allow-Origin' header contains multiple values 'http://domain1.com, http://domain2.com', but only one is allowed. Origin 'http://domain2.com' is therefore not allowed access.
LOG

这就尴尬了是不是。

httphttpshttp://https://

课外学习

跨域的设置还有更高级的,您可以:

跨域资源共享 CORS 详解

HTTP访问控制(CORS)

3、善用搜索


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!