nginx 代理情况下 jsp request.getServerName 得不到服务器ip

本文探讨了在使用代理服务器时如何正确配置Host头来确保应用程序能够获取到正确的客户端请求信息。通过分析Tomcat源码及nginx配置示例,解释了为何在未配置转发Host时获取到的是127.0.0.1,并提供了具体的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

过程:

浏览器------>代理-------->真实应用服务器

浏览器发送请求给代理,代理发送请求给应用服务器,代理将应用服务器返回的内容返回给浏览器。

情景再现:

在有代理的情况下,request.getServerName()得到的ip地址是127.0.0.1,解决办法就是,nginx中配置 proxy_set_header Host $Host,这个配置的意思就是代理转发客户端请求header中的Host。

原因分析:

不配置转发Host,为什么得到的地址是127.0.0.1?

通过查看Tomcat的源码得知,request首先会判断http heder中的host,如果没有,那么就获取本机的ip地址,因为代理没有配置转发host,所以得到的是127.0.0.1。

源码分析的具体过程:

因为项目使用的是maven,所以查看源码比较方便

ServletRequest-----HttpServletRequestImpl------HttpServerExchange

以下是servlet3.0的源码:

 /**
     * Return the host that this request was sent to, in general this will be the
     * value of the Host header, minus the port specifier.
     * <p/>
     * If this resolves to an IPv6 address it will not be enclosed by square brackets.
     * Care must be taken when constructing URLs based on this method to ensure IPv6 URLs
     * are handled correctly.
     *
     * @return The host part of the destination address
     */
    public String getHostName() {
        String host = requestHeaders.getFirst(Headers.HOST);
        if (host == null) {
            host = getDestinationAddress().getAddress().getHostAddress();
        } else {
            if (host.startsWith("[")) {
                host = host.substring(1, host.indexOf(']'));
            } else if (host.indexOf(':') != -1) {
                host = host.substring(0, host.indexOf(':'));
            }
        }
        return host;
    }

解决方案

nginx中配置proxy_set_header Host $Host

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值