linux下配置nginx反向代理例子
Posted 我俩绝配
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux下配置nginx反向代理例子相关的知识,希望对你有一定的参考价值。
官方说明:
例子:
虚拟机ip:192.168.85.3,物理机VMware Network Adapter VMnet8 ip:192.168.85.1
1,准备tomcat
准备一tomcat,端口,8080
准备一Jsp,用于获取客户端真实IP和nginx IP ,test.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Test Page</title> </head> <body> Test1 Page!!!<br/> remote ip : <%-- <%=request.getHeader("X-real-ip") %> --%> <br/> nginx server ip : <%=request.getRemoteAddr()%> </body> </html>
将test.jsp 上传到 tomcat的/ROOT目录下。
2,配置nginx
注意,反向代理之后获取到客户端IP地址为nginx服务器地址,这里需要nginx进行forward,设置真实的ip地址。往请求头set一变量 X-real-ip ,值取客户端ip,这样就可以在jsp中获取该变量:
proxy_set_header X-real-ip $remote_addr;
匹配.jsp结尾的请求:
location ~ \\.jsp$
3,测试
启动tomcat,启动nginx,浏览器访问:http://192.168.85.3:70/test.jsp
在Java里面一般有一个工具类来获取 IP:
public class IpUtils { private IpUtils() { } public static String getIpAddr(HttpServletRequest request) { if (request == null) { return "unknown"; } String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }
欢迎关注个人公众号一起交流学习:
以上是关于linux下配置nginx反向代理例子的主要内容,如果未能解决你的问题,请参考以下文章