用模板建商城购物网站,便利的龙岗网站设计,福田区住房和建设局网站,百度seo优化推广软件作者简介#xff1a;大家好#xff0c;我是撸代码的羊驼#xff0c;前阿里巴巴架构师#xff0c;现某互联网公司CTO 联系v#xff1a;sulny_ann#xff08;17362204968#xff09;#xff0c;加我进群#xff0c;大家一起学习#xff0c;一起进步#xff0c;一起对抗…作者简介大家好我是撸代码的羊驼前阿里巴巴架构师现某互联网公司CTO 联系vsulny_ann17362204968加我进群大家一起学习一起进步一起对抗互联网寒冬 # 序言 使用Nginx反向代理可以解决跨域无权和Session丢失的问题十分方便。下面我们以前后端分离为案例展开Nginx的使用教程。 # 配置和启动Nginx 下载地址 Nginx下载传送门http://nginx.org/en/download.html 注意事项下载之后记得解压到全英文路径避免中文路径导致Nginx启动失败。 修改配置 打开nginx.conf 清空配置项然后将下面的配置信息原封不动拷贝进去 worker_processes 1;
events { worker_connections 1024;}
http { include mime.types; default_type application/octet-stream;sendfile on; keepalive_timeout 65;#前端页面服务器 server { #监听端口和域名 listen 7000; server_name localhost;#添加头部信息 proxy_set_header Cookie $http_cookie; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #添加拦截路径和代理地址 location /api/ { proxy_pass http://localhost:8080/; #注意使用代理地址时末尾记得加上斜杠/。 } #添加拦截路径和根目录 location / { root html/hehe; #注意使用/拦截全路径的时候记得放在最后。 index index.html index.htm; #index表示首页 } }} 快速启动 在Windows 环境中 快速启动Nginx右键管理员模式运行nginx.exe。 快速关闭Nginx在nginx主目录添加关闭Nginx的命令。
其中结束Nginx.bat的具体内容如下 taskkill /f /im nginx.exe 使用命令快速关闭Nginx # 部署前端页面 前后端分离后可以直接将静态资源例如前端页面部署到Nginx的html目录。这里我们在$nginx_home/html目录下创建一个名为hehe的文件夹并添加一个页面index.html用于跨域访问测试index页面内容如下
!DOCTYPE htmlhtml langenhead meta charsetUTF-8/ titlePage Index/title/headbodyh2前台系统7000/h2p idinfo1/pp idinfo2/p/body
script srcjs/jquery.js/scriptscript $.ajax({ url: http://localhost:7000/api/user/login/verifyCode, type: POST, success: function (data) { //1.获取验证码 $(#info1).html(跨域访问成功:verifyCode: data); //2.核对验证码 $.ajax({ url: http://localhost:7000/api/user/login/checkVerifyCode, type: POST, success: function (data) { $(#info2).html(跨域访问成功:checkVerifyCode: data); } }); }, error: function (data) { $(#info1).html(跨域失败!!); } });/script
/html # 启动后端系统 首先在POM文件添加Web依赖然后编写控制层提供对外的访问接口。默认启动端口是8080.
package com.hehe;
SpringBootApplicationRestControllerRequestMapping(/user/login/*)public class SpringBootNginxApplication { //在拦截器打印访问URL Bean public WebMvcConfigurer webMvcConfigurer() { return new WebMvcConfigurer() { Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerInterceptor() { Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Nullable Exception ex) throws Exception { if(response.getStatus()/1004){ System.err.println(访问URL:request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)); }else { System.out.println(访问URL:request.getRequestURI()); } } }); } }; } //提供验证码 RequestMapping(verifyCode) public String verifyCode(HttpServletRequest request) { request.getSession().setAttribute(verifyCode, N7GX); return request.getSession().getId() : request.getSession().getAttribute(verifyCode); }//核对验证码 RequestMapping(checkVerifyCode) public String checkVerifyCode(HttpServletRequest request) { return request.getSession().getId() : request.getSession().getAttribute(verifyCode); }public static void main(String[] args) { SpringApplication.run(SpringBootNginxApplication.class, args); }} # 测试跨域访问 打开浏览器访问 http://localhost:7000/api/user/login/verifyCode 可以看到后台获取的Session和第一次生成的验证码。如图: 打开浏览器访问 http://localhost:7000/api/user/login/checkVerifyCode 可以看到后台获取的Session和第二次取出的验证码。 由上图可以看到跨域访问成功并且Session没有丢失。 # Nginx跨域总结 Nginx VS CORS 简单来说Nginx是间接跨域而CORS则实现了直接跨域。Nginx的反向代理“欺诈了”浏览器所以浏览器和服务器都认为是同源访问所以Session不会丢失。 PS如果发生跨域访问服务器会每次都创建新的Session所以才造成了前后端分离的Session丢失问题。 至于CORS这种跨域机制的安全性和灵活性更高但需要自己解决跨域访问Session丢失的问题通常情况可以采用SessionRedis来实现Session共享。 Nginx跨域实现过程: 第1步http://localhost:7000/index.html 第2步http://localhost:7000/api/user/login/verifyCode 第1步是打开页面第2步是在这个页面发起AJAX请求并且请求的域名端口均与当前访问页面相同属于同源操作所以浏览器不会报出跨域禁止的错误。 第3步http://localhost:8080/user/login/verifyCode 第3步是本案例最为关键的一步真正的跨域操作由Nginx的proxy_pass进行完成并成功将验证码信息以代理的身份返回给浏览器让浏览器处于同源访问后台的错觉。打开F12可以看到代理服务器 关于proxy_pass 斜杠/ 的坑 通常情况下建议大家在代理地址末尾加上/ 表示转发后就是proxy_pass直接拼接映射路径。 Nginx代理效果 转发前URLhttp://localhost:7000/api/user/login/verifyCode 转发后URLhttp://localhost:8080/hehe/user/login/verifyCode
server { listen 7000; server_name localhost; #正确示范: 末尾加斜杠/ location /api/ { proxy_pass http://localhost:8080/hehe/; } } 如果代理地址末尾没有加斜杠的话表示转发后也是proxy_pass直接拼接映射路径但是拼接的时候会少了个/这样会引发访问路径错误。 Nginx代理效果 转发前URLhttp://localhost:7000/api/user/login/verifyCode 转发后URLhttp://localhost:8080/heheuser/login/verifyCode
server { listen 7000; server_name localhost; #错误示范: 末尾无斜杠 location /api/ { proxy_pass http://localhost:8080/hehe; } } 为了更方便大家看到在Nginx调整了proxy_pass有无斜杠的区别楼主在控制台打印了每次请求访问的URL地址这样更加清晰 具体做法关闭Nginx 将代理地址修改为proxy_pass
http://localhost:8080/hehe 然后启动Nginx在浏览器访问http://localhost:7000/api/user/login/verifyCode然后查看控制台打印的URL信息。清楚的看到了因为少了斜杠而导致拼接成错误路径如下