Tomcat gets the client domain name for the Nginx reverse proxy

  • 2020-12-22 17:51:13
  • OfStack

The problem

After the Nginx reverse proxy, the Tomcat application passes request.getHeader("host") I got host of Nginx, not the real domain name on the address bar of the client browser.

For example, on one server, the port number of Tomcat is 8080, the port number of Nginx is 80, and the port number of Nginx reverse proxy is 8080.


server {
  listen 80;
  location / {
    proxy_pass http://127.0.0.1:8080;
  }
}

Open it with a browser on another machine http://haha/test Access the application under Tomcat to get the client domain name.


System.out.println(request.getHeader("host"));

The result is:

[

localhost:8080

]

The cause of the problem

The reverse proxy for Nginx is essentially a bridge between the client (typically a browser) that accesses the Nginx server, and the Nginx that accesses the Web application server. For Web applications, this time HTTP requests the client as Nginx rather than the real client browser. If no special processing is done, Web applications will treat Nginx as the client of the request and get some information of Nginx.

Problem solving

Nginx Configuration HTTP Header. Host contains the client's real domain name and port number


proxy_set_header Host $http_host;

Tomcat gets client information from HTTP Header, which is passed from Nginx.


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

conclusion


Related articles: