Tomcat:getHeader(" Host")与getServerName() [英] Tomcat: getHeader("Host") vs. getServerName()

查看:570
本文介绍了Tomcat:getHeader(" Host")与getServerName()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从多个域提供的Tomcat应用程序。以前的开发人员构建了一个返回应用程序URL的方法(见下文)。在方法中,他们请求服务器名称( request.getServerName()),从适当的位置返回 httpd.conf中的 ServerName 文件。

I've got a Tomcat app that is being served up from multiple domains. Previous developers built a method to return the application URL (see below). In the method they request the server name (request.getServerName()) which, appropriately, returns the ServerName from the httpd.conf file.

但是,我不希望这样。我想要的是浏览器发送请求的主机名,即浏览器从哪个域访问应用程序。

However, I don't want that. What I want is the host name that the browser sent the request to, i.e. whichever domain the browser is accessing the application from.

我试过 getHeader(主机),但仍然返回 ServerName httpd.conf 文件中设置。

I tried getHeader("Host"), but that is still returning the ServerName set in the httpd.conf file.

而不是 request.getServerName(),我应该使用什么来获取浏览器发送请求的服务器名称?

Instead of request.getServerName(), what should I use to get the server name that the browser sent the request to?

例如:


  • httpd.conf中的ServerName www.myserver.net

  • 用户访问Tomcat应用程序 www.yourserver.net

  • ServerName in httpd.conf: www.myserver.net
  • User accesses Tomcat app on www.yourserver.net

我需要返回 www.yourserver.net www.myserver.net request.getServerName()调用似乎只返回 www.myserver.net

I need to return www.yourserver.net NOT www.myserver.net. The request.getServerName() call only seems to return www.myserver.net

/**
 * Convenience method to get the application's URL based on request
 * variables.
 * 
 * @param request the current request
 * @return URL to application
 */
public static String getAppURL(HttpServletRequest request) {
    StringBuffer url = new StringBuffer();
    int port = request.getServerPort();
    if (port < 0) {
        port = 80; // Work around java.net.URL bug
    }
    String scheme = request.getScheme();
    url.append(scheme);
    url.append("://");
    url.append(request.getServerName());
    if (("http".equals(scheme) && (port != 80)) || ("https".equals(scheme) && (port != 443))) {
        url.append(':');
        url.append(port);
    }
    url.append(request.getContextPath());
    return url.toString();
}

提前致谢!

推荐答案

您需要确保 httpd 通过提供的主机标头由客户端到Tomcat。最简单的方法(假设您使用 mod_proxy_http - 您没有说)具有以下内容:

You need to ensure that httpd passes the Host header provided by the client to Tomcat. The easiest way (assuming you are using mod_proxy_http - you didn't say) is with the following:

ProxyPreserveHost On

这篇关于Tomcat:getHeader(&quot; Host&quot;)与getServerName()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆