#先配置Nginx
先举例 以下是我们常用的nginx站点配置(PHP网站为例)
server {
listen 监听端口;
server_name 域名部分;
set $root_path 目录部分;
root $root_path;
index index.php index.html;
location / {
if ($request_method = 'OPTIONS') {
add_header Access-Control-Allow-Origin $http_origin;
add_header Access-Control-Allow-Methods OPTIONS,HEAD,GET,POST,DELETE,PUT,PATCH;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Max-Age 1728000;
add_header Access-Control-Allow-Headers authorization,content-type,x-requested-with,Accept,Authorization,Origin,Referer,X-Csrf-Token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;
return 200;
}
try_files $uri $uri/ /index.php?$query_string;
}
location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
root $root_path;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
其中 以下部分就是针对CORS跨域的解决方法
其中的 $http_origin 是nginx的一个变量 这样设置可以允许所有来源的请求 主要是测试服务器和生产服务器不在一起的情况就不用改配置了 这个变量也可以替换成具体的域名
#下面配置PHP部分
在php代码的入口位置增加如下配置即可
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: ".$origin);
header("Access-Control-Allow-Methods: OPTIONS,HEAD,GET,POST,DELETE,PUT,PATCH");
header("Access-Control-Allow-Headers: authorization,content-type,x-requested-with,Accept,Authorization,Origin,Referer,X-Csrf-Token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Requesst-Header: Content-Type, content-type, X-Client-Header");
header("Access-Control-Max-Age: 1728000");
header("Access-Control-Request-Method: POST, GET, PUT, DELETE, PATCH, OPTIONS");
本文参看了 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS 这篇文章的帮助,有关CORS问题可以进一步了解