linux下配置nginx反向代理例子

 

官方说明:

linux下配置nginx反向代理例子_第1张图片

例子:

虚拟机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 Pagetitle>
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$

linux下配置nginx反向代理例子_第2张图片

3,测试

启动tomcat,启动nginx,浏览器访问:http://192.168.85.3:70/test.jsp 

linux下配置nginx反向代理例子_第3张图片

 在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反向代理例子)