Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat: getHeader("Host") vs. getServerName()

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.

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

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

For example:

  • ServerName in httpd.conf: www.myserver.net
  • User accesses Tomcat app on www.yourserver.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();
}

Thanks in advance!

like image 504
Mark Hall Avatar asked May 02 '12 03:05

Mark Hall


1 Answers

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
like image 184
Mark Thomas Avatar answered Sep 19 '22 02:09

Mark Thomas