php 解决跨域
- 简单跨域问题
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods:POST");
允许自定义请求头:方式一
header("Access-Control-Allow-Headers:x-requested-with,content-type,xxx自定义请求头xx");
- 非简单跨域
非简单请求每次会发出两次请求,预检请求和正常请求
缓存预检命令1小时,取消options请求
header("Access-Control-Max-Age:3600");
当携带cookie时origin必须全匹配,不能使用*,而且要增加Access-Control-Allow-Credentials
$origin = $_SERVER['HTTP_ORIGIN'];
if(isset($origin)){//跨域时$origin不等于null
header("Access-Control-Allow-Origin:$origin");
}
header("Access-Control-Allow-Credentials: true");//enable cookie
nginx 解决跨域
server {
listen 8090;
server_name 127.0.0.1;
root /var/www/public;
index index.html index.php index.htm;
location / {
proxy_pass http://localhost:8080/;
add_header Access-Control-Allow-Methods * always;
add_header Access-Control-Max-Age 3600 always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Headers $http_access_control_request_headers always;
if ($request_method = OPTIONS){
return 200;
}
}
}
- 反向代理----隐藏跨域
server {
listen 80;
server_name 127.0.0.1;
root /var/www/public;
location / {
proxy_pass http://localhost:8081/;
}
location /ajaxserver {
proxy_pass http://localhost:8080/test/;
}
}