Administrator
发布于 2023-02-17 / 69 阅读
0
0

【Nginx】如何获取客户端真实IP、域名、协议、端口

【Nginx】如何获取客户端真实IP、域名、协议、端口

工作中实际使用,获取客户端实际ip

refer to : https://juejin.cn/post/6844903688037908488

1.编译时,需要增加realip这个module

./configure --with-http_realip_module

2.nginx.conf如下:


#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 backend {
        server 192.168.10.8:8069;
    }
	
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
		proxy_pass       http://backend;
			proxy_set_header Host            $host;
            proxy_set_header  X-Real-IP  $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
			real_ip_header    X-Forwarded-For;
			real_ip_recursive on;
            root   html;
            index  index.html index.htm;
        }

        #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;
    #    }
    #}

}

3.测试

1.13.16.140发起请求 ----> 221.181.222.135(192.168.10.66)----> 192.168.10.8(Java服务)

在1.13.16.140服务器上,执行以下命令

curl http://221.181.222.135:9898/test/realIp

Java服务的controller层,使用HttpServletRequest 获取header如下:

image-20230616152342916

其中1.13.16.140就是我们真实的客户端ip

Nginx获取客户端信息

注意:本文中的客户端信息指的是:客户端真实IP、域名、协议、端口。

Nginx反向代理后,Servlet应用通过request.getRemoteAddr()取到的IP是Nginx的IP地址,并非客户端真实IP,通过request.getRequestURL()获取的域名、协议、端口都是Nginx访问Web应用时的域名、协议、端口,而非客户端浏览器地址栏上的真实域名、协议、端口。

直接获取信息存在哪些问题?

例如在某一台IP为192.168.1.100的服务器上,Jetty或者Tomcat端口号为8080,Nginx端口号80,Nginx反向代理8080端口:

server {
listen 80;
location / {
proxy_pass http://127.0.0.1:8080; # 反向代理应用服务器HTTP地址
}
}
在另一台机器上用浏览器打开http://192.168.1.100/test访问某个Servlet应用,获取客户端IP和URL:

System.out.println("RemoteAddr: " + request.getRemoteAddr());
System.out.println("URL: " + request.getRequestURL().toString());
打印的结果信息如下:

RemoteAddr: 127.0.0.1
URL: http://127.0.0.1:8080/test
可以发现,Servlet程序获取到的客户端IP是Nginx的IP而非浏览器所在机器的IP,获取到的URL是Nginx proxy_pass配置的URL组成的地址,而非浏览器地址栏上的真实地址。如果将Nginx用作https服务器反向代理后端的http服务,那么request.getRequestURL()获取的URL是http前缀的而非https前缀,无法获取到浏览器地址栏的真实协议。如果此时将request.getRequestURL()获取得到的URL用作拼接Redirect地址,就会出现跳转到错误的地址,这也是Nginx反向代理时经常出现的一个问题。

如何解决这些问题?

既然直接使用Nginx获取客户端信息存在问题,那我们该如何解决这个问题呢?

我们整体上需要从两个方面来解决这些问题:

(1)由于Nginx是代理服务器,所有客户端请求都从Nginx转发到Jetty/Tomcat,如果Nginx不把客户端真实IP、域名、协议、端口告诉Jetty/Tomcat,那么Jetty/Tomcat应用永远不会知道这些信息,所以需要Nginx配置一些HTTP Header来将这些信息告诉被代理的Jetty/Tomcat;

(2)Jetty/Tomcat这一端,不能再获取直接和它连接的客户端(也就是Nginx)的信息,而是要从Nginx传递过来的HTTP Header中获取客户端信息。

具体实践

配置nginx
首先,我们需要在Nginx的配置文件nginx.conf中添加如下配置。

proxy_set_header Host $http_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;
各参数的含义如下所示。

Host包含客户端真实的域名和端口号;
X-Forwarded-Proto表示客户端真实的协议(http还是https);
X-Real-IP表示客户端真实的IP;
X-Forwarded-For这个Header和X-Real-IP类似,但它在多层代理时会包含真实客户端及中间每个代理服务器的IP。
此时,再试一下request.getRemoteAddr()和request.getRequestURL()的输出结果:



RemoteAddr: 127.0.0.1
URL: http://192.168.1.100/test
可以发现URL好像已经没问题了,但是IP还是本地的IP而非真实客户端IP。但是如果是用Nginx作为https服务器反向代理到http服务器,会发现浏览器地址栏是https前缀但是request.getRequestURL()获取到的URL还是http前缀,也就是仅仅配置Nginx还不能彻底解决问题。

通过Java方法获取客户端信息
仅仅配置Nginx不能彻底解决问题,那如何才能解决这个问题呢?一种解决方式就是通过Java方法获取客户端信息,例如下面的Java方法。

/***
 * 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP
 */
public static String getClientIP(HttpServletRequest request) {
    String fromSource = "X-Real-IP";
    String ip = request.getHeader("X-Real-IP");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	ip = request.getHeader("X-Forwarded-For");
    	fromSource = "X-Forwarded-For";
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	ip = request.getHeader("Proxy-Client-IP");
    	fromSource = "Proxy-Client-IP";
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	ip = request.getHeader("WL-Proxy-Client-IP");
    	fromSource = "WL-Proxy-Client-IP";
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    	ip = request.getRemoteAddr();
    	fromSource = "request.getRemoteAddr";
    }
    return ip;
}

这种方式虽然能够获取客户端的IP地址,但是我总感觉这种方式不太友好,因为既然Servlet API提供了request.getRemoteAddr()方法获取客户端IP,那么无论有没有用反向代理对于代码编写者来说应该是透明的。

接下来,我就分别针对Jetty服务器和Tomcat服务器为大家介绍下如何进行配置才能更加友好的获取客户端信息。

Jetty服务器
在Jetty服务器的jetty.xml文件中,找到httpConfig,加入配置:

...

重新启动Jetty,再用浏览器打开http://192.168.1.100/test测试,结果:

RemoteAddr: 192.168.1.100
URL: http://192.168.1.100/test
此时可发现通过request.getRemoteAddr()获取到的IP不再是127.0.0.1而是客户端真实IP,request.getRequestURL()获取的URL也是浏览器上的真实URL,如果Nginx作为https代理,request.getRequestURL()的前缀也会是https。

另外,Jetty将这个功能封装成一个模块:http-forwarded。如果不想改jetty.xml配置文件的话,也可以启用http-forwarded模块来实现。

例如可以通过命令行启动Jetty:

java -jar start.jar --module=http-forwarded
更多Jetty如何启用模块的相关资料可以参考:http://www.eclipse.org/jetty/documentation/current/startup.html

Tomcat
和Jetty类似,如果使用Tomcat作为应用服务器,可以通过配置Tomcat的server.xml文件,在Host元素内最后加入:

<Valve className="org.apache.catalina.valves.RemoteIpValve" />

评论