页面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配置解决跨域问题的更多相关文章

  1. 使用Nginx来解决跨域的问题

    使用Nginx来解决跨域的问题 nginx的版本:(查看nginx命令: /usr/local/nginx/sbin/nginx -v) nginx/1.4.3 问题是:前端项目域名是 a.xxxx. ...

  2. 【Nginx】使用Nginx如何解决跨域问题?看完这篇原来很简单!!

    写在前面 当今互联网行业,大部分Web项目基本都是采用的前后端分离模式.前端为H5项目,后端为Java.PHP.Python等项目.而且大部分后端服务并不会只部署一套服务,而是会采用Nginx对后端服 ...

  3. 一篇文章让你搞懂如何通过Nginx来解决跨域问题

    Nginx跨域实现   首先大家要搞清楚什么是跨域,为什么会有跨域情况的出现.哪些情况属于跨域? 跨域:由于浏览器的同源策略,即属于不同域的页面之间不能相互访问各自的页面内容 注:同源策略,单说来就是 ...

  4. vue webpack配置解决跨域问题

    现在基本项目都是实行前后端分离的原则,不管是ng 或者是vue 在开发中都无法避免跨域的这个问题 本人刚上手第一个vue项目,在调用api的时候出现了跨域的这个问题 这是封装好一个简单的post 请求 ...

  5. vue项目开发,用webpack配置解决跨域问题

    今天在本地开发时候碰到了跨域的问题,突然觉着跨域问题在所难免啊,之前没有没有碰到总觉着解决跨域很高大上的样纸,其实就是受限于网络的同源策略,跨域前后端都可以进行处理. 1,后端更改header hea ...

  6. nginx 配置ajax跨域访问php接口

    在nginx.conf里面,找到server项,并在里面添加如下配置 location ~ \.php?($|/) { #try_files $uri =; #handel cosr by mao a ...

  7. 服务端 Cros 配置解决跨域

    <system.webServer> <httpProtocol> <customHeaders> <remove name="Access-Con ...

  8. Nginx配置解决NetCore的跨域

    使用Nginx配置解决NetCore的跨域 废话不多说,直接上Nginx配置 server { listen 80; server_name 你的Id或域名; location / { add_hea ...

  9. 【手摸手,带你搭建前后端分离商城系统】02 VUE-CLI 脚手架生成基本项目,axios配置请求、解决跨域问题

    [手摸手,带你搭建前后端分离商城系统]02 VUE-CLI 脚手架生成基本项目,axios配置请求.解决跨域问题. 回顾一下上一节我们学习到的内容.已经将一个 usm_admin 后台用户 表的基本增 ...

  10. Vue使用Axios实现http请求以及解决跨域问题

    Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中.Axios的中文文档以及github地址如下: 中文:https://www.kancloud.cn/y ...

随机推荐

  1. 字节过滤流->缓冲流 BufferedOutputStream 用法:

    1创建字节输出节点流 :FileoutputStream fos = new FileoutputStream("文件输入的路径",true);(true表示追加,false表示覆 ...

  2. C# 类库 dll 读取配置文件信息

    一:给 C# 类库 dll 添加配置文件并读取配置信息 效果: 1.给类库程序添加配置文件,并命名为:类库名.DLL.config 如上面效果图,类库为:API.dll ,那么其对应的类库配置文件为: ...

  3. OpenCV图像拼接函数

    图像拼接函数 第一种方法:通过遍历图像,将待拼接的图像每个像素赋值给输出图像 //图像拼接函数 //imageVector 输入图像数组 //outputImage 输出图像 //colCount_ ...

  4. 论zzy的苏州话

    乘地铁(ceng) - 盛饭(seng) 无法无天 - 12345 掀被子 - 先干嘛,再干嘛 ?待更新

  5. lc.209 长度最小的子数组

    题目 给定一个含有 n 个正整数的数组和一个正整数 target . 找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, n ...

  6. OSPF V3协议简介

     LSA1/LSA 2在ospfv3中,变成了只携带拓扑信息,区域内的路由信息注意到LSA 9中

  7. iframe跨域通信window.postMessage()方法

    需求:A页面中要嵌入一个iframe,这个iframe是B页面,此时A页面需要得到B页面的一些信息. window.postMessage() 我们都知道浏览器的同源策略,即对于两个不同页面的脚本,只 ...

  8. SpringBoot之基于idea搭建ssm(maven)

    此次目标为搭建一个简单的基于springboot的ssm(spring + springmvc + mybatis)的maven项目,使用的数据库为mysql. 最终项目目录结构 创建过程 1.项目创 ...

  9. LaravelORM 中的 withSum , withAvg, withMax,withMin 的实现

    Orm::withCount(['relation as relation_sum' =>function($query){ $query->select(DB::raw("su ...

  10. 记一次dubbo服务丢失的问题排查

    主要环境与用到的(关键)组件: Springboot2.3.2 其中,dubbo-spring-boot-starter版本为2.7.8 zookeeper3.5.9 首先是服务报错: No prov ...