巧用Nginx配置解决跨域问题
页面nginx配置
1,前端页面放在域名根目录,比如,http://www.xuecheng.com/ ,对应的nginx配置:
#门户
location / {
alias D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
index index.html;
}
页面目录:

接口nginx配置
2,前端请求接口路径,在域名后面加一个目录
url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址
function login(){
var uname = $("#username").val();
var pwd = $("#password").val();
$.ajax({
url : "http://www.xuecheng.com/api/auth/oauth/token",//发送请求的地址
type: "post",
dataType: "json",
data : "username="+uname+"&password="+pwd+"&grant_type=password",
beforeSend:function (request) {
// 如果后台没有跨域处理,这个自定义
request.setRequestHeader("Authorization","Basic RG9jV2ViQXBwOjEyMzQ1Ng==");
// 禁用按钮,防止重复提交
$("#submit").attr({ disabled: "disabled" });
},
error : function() {
alert("error occured!!!");//请求失败时弹出的信息
},
success : function(data) {//返回的信息展示出来
alert(JSON.stringify(data))
}
});
};
nginx 对api接口配置
location /api/ {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_pass http://apiserver/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
}
其中的
$http_origin
$http_origin并不是nginx的内置参数,nginx支持取自定义的参数值,$http_XXX这个格式是nginx取请求中header的XXX的值的。这里取的是origin,而一般跨域请求都会将请求的来源放在origin中(浏览器会往跨域请求的header上面加origin这个header)。

这样配置的话,前端页面在域名下:www.xuecheng.com,而访问的接口则是www.xuecheng.com/api/xxx ,这样就不存在跨域问题了,
其实nginx不配置 Access-Control-Allow-Origin也没事,因为前后端在一个域下了。
注意事项
如果你前后端访问存在跨域问题,而且你需要使用cookie,后端要想获取到前端携带过来的cookie,前后端都要做配置:
前端:
var xhr = new XMLHttpRequest()
xhr.withCredentials = true
xhr.open('GET', 'http://localhost:8888/', true)
xhr.send(null)
后端:
Access-Control-Allow-Origin: http://www.abc.com(这里必须域名不能是*)
Access-Control-Allow-Credentials: true
完整nginx配置
#user nobody;
worker_processes 1; #error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info; #pid logs/nginx.pid; events {
worker_connections 1024;
} http {
include mime.types;
default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on;
#tcp_nopush on; #keepalive_timeout 0;
keepalive_timeout 65; #gzip on; #微服务网关
upstream apiserver{
server 127.0.0.1:50101;
}
server {
listen 80;
server_name www.xuecheng.com; ssi on;
ssi_silent_errors on; #charset koi8-r; #access_log logs/host.access.log main; #门户
location / {
alias D:/Z_lhy/SpringCloud/xuecheng_online/www/xc-ui-pc-static-portal/;
index index.html;
}
#location / {
# root /neworiental/www/jiaofu;
# index index.html;
# try_files $uri /index.html;
#} # proxy_pass末尾有/,请求地址:http://localhost/api/test,转发地址:http://127.0.0.1:8000/test
location /api/ {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain; charset=utf-8';
add_header 'Content-Length' 0;
return 204;
}
proxy_pass http://apiserver/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5;
} location ^~ /openapi/auth/ {
proxy_pass http://apiserver/auth/;
} #error_page 404 /404.html; # redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
} # proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#} # deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
} # another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias; # location / {
# root html;
# index index.html index.htm;
# }
#} # HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost; # ssl_certificate cert.pem;
# ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on; # location / {
# root html;
# index index.html index.htm;
# }
#} }
参考:
正确的Nginx跨域配置:https://blog.csdn.net/envon123/article/details/83270277
跨域资源共享(CORS)安全性:https://blog.csdn.net/weixin_43964148/article/details/109352413
巧用Nginx配置解决跨域问题的更多相关文章
- 使用Nginx来解决跨域的问题
使用Nginx来解决跨域的问题 nginx的版本:(查看nginx命令: /usr/local/nginx/sbin/nginx -v) nginx/1.4.3 问题是:前端项目域名是 a.xxxx. ...
- 【Nginx】使用Nginx如何解决跨域问题?看完这篇原来很简单!!
写在前面 当今互联网行业,大部分Web项目基本都是采用的前后端分离模式.前端为H5项目,后端为Java.PHP.Python等项目.而且大部分后端服务并不会只部署一套服务,而是会采用Nginx对后端服 ...
- 一篇文章让你搞懂如何通过Nginx来解决跨域问题
Nginx跨域实现 首先大家要搞清楚什么是跨域,为什么会有跨域情况的出现.哪些情况属于跨域? 跨域:由于浏览器的同源策略,即属于不同域的页面之间不能相互访问各自的页面内容 注:同源策略,单说来就是 ...
- vue webpack配置解决跨域问题
现在基本项目都是实行前后端分离的原则,不管是ng 或者是vue 在开发中都无法避免跨域的这个问题 本人刚上手第一个vue项目,在调用api的时候出现了跨域的这个问题 这是封装好一个简单的post 请求 ...
- vue项目开发,用webpack配置解决跨域问题
今天在本地开发时候碰到了跨域的问题,突然觉着跨域问题在所难免啊,之前没有没有碰到总觉着解决跨域很高大上的样纸,其实就是受限于网络的同源策略,跨域前后端都可以进行处理. 1,后端更改header hea ...
- nginx 配置ajax跨域访问php接口
在nginx.conf里面,找到server项,并在里面添加如下配置 location ~ \.php?($|/) { #try_files $uri =; #handel cosr by mao a ...
- 服务端 Cros 配置解决跨域
<system.webServer> <httpProtocol> <customHeaders> <remove name="Access-Con ...
- Nginx配置解决NetCore的跨域
使用Nginx配置解决NetCore的跨域 废话不多说,直接上Nginx配置 server { listen 80; server_name 你的Id或域名; location / { add_hea ...
- 【手摸手,带你搭建前后端分离商城系统】02 VUE-CLI 脚手架生成基本项目,axios配置请求、解决跨域问题
[手摸手,带你搭建前后端分离商城系统]02 VUE-CLI 脚手架生成基本项目,axios配置请求.解决跨域问题. 回顾一下上一节我们学习到的内容.已经将一个 usm_admin 后台用户 表的基本增 ...
- Vue使用Axios实现http请求以及解决跨域问题
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中.Axios的中文文档以及github地址如下: 中文:https://www.kancloud.cn/y ...
随机推荐
- 鸿蒙hi3861V100开发板问题记录
1.引脚复用 2.引脚复用方法: 1.看业务代码使用的是uart几,如使用的是uart2(实测可用uart1 tx为GPIO6, rx为GPIO5:uart2 tx为GPIO11,rx为GPIO12) ...
- 学习JavaScript第五周
MySQL基本内容: 访问:2种 1.图形化界面 - 傻瓜式 要求:同时打开apache和mysql 访问:127.0.0.1:端口号/phpmyadmin localhost:端口号 ...
- 第12组 Beta冲刺 (5/5)
1.1基本情况 ·队名:美少女战士 ·组长博客:https://www.cnblogs.com/yaningscnblogs/p/14016978.html ·作业博客:https://edu.cnb ...
- C++学习流程
一.初级入门阶段 数据类型.变量.内存布局.指针基础: 字符串.一维数组.二维数组: 一级指针,二级指针,三级指针,N级指针概念,指针数组和数组指针: 结构体.文件的使用: 动态库的封装和设计: 函数 ...
- @DeclareParents声明对象的AOP
今天在使用@DeclareParents时,使用AspectJ拓展对象的接口 public interface Encoreable { void nextPerformance(); } @Comp ...
- SAP B1 增加或删除单据,或者是新增修改BOM清单,报错‘出现内部错误时’,一般是控制过程 SBO_SP_TransactionNotification 里面的代码有问题,执行不下去了,因此一行行检查SQL代码,一般就能发现错误所在。
SAP B1 增加或删除单据,或者是新增修改BOM清单,报错'出现内部错误时',一般是控制过程 SBO_SP_TransactionNotification 里面的代码有问题,执行不下去了,因此一行行 ...
- 关于安装Wind金融终端后,启动QT后频繁跳出WDF.dll文件注册成功窗口的问题
安装Wind金融终端后,启动QT后频繁跳出WDF.dll文件注册成功窗口的信息. 经过排查后发现,主要问题出在系统环境变量上. 安装了wind金融终端后,用户系统环境变量PATH里多了两个wind相关 ...
- revit转tileset 3dmax转tileset cesium展示
使用revit软件导出fbx模型: 使用glTFExport导出gltf模型,导出的gltf模型具有属性.但是此处导出gltf模型,不是为了在cesium中加载该gltf模型,主要目的是获取组件属性信 ...
- kg打怪升级
1.kaggle notebook容易断[continue部署] 2.换预训练模型[提交试试] 3.换fold次数
- Linux 截图快捷键 - 搬运
Linux 截图快捷键 转自:linux 截图快捷键 环境 Linux Mint 21.1 1. Prt ScSysRq ---->全屏截图2. Shift+Prt ScSysRq ----& ...