search
HomeOperation and MaintenanceNginxHow to use Nginx as reverse proxy for Tomcat server

1) Of course you need to download the software you want to use. Go to the nginx official website for the next one. http://nginx.org/en/download.html can be found here. The version I am using now is 1.1.7, but basically all future versions are compatible, and what we are using does not involve too low-level aspects, so there should be no changes. Here, since mine is Windows, of course I download the Windows version. After downloading, you need to start it first. Enter the nginx folder and start nginx directly. For example, after downloading, I put it in d:\software\developertools\server\nginx-1.1.7, directly cmd and then cd d:\software\developertools\server\nginx-1.1.7. Some people who are not used to the command line may be surprised. It doesn't proceed to that folder. Windows will not jump between partitions unless you specify it yourself. So we have to directly d: as follows:

How to use Nginx as reverse proxy for Tomcat server

Then, we start nginx directly. Here you may see a window flashing by. According to our use of tomcat If the experience passes by in a flash, it proves that something is wrong, right? But it's not.

How to use Nginx as reverse proxy for Tomcat server

#At this time we open the task manager and can see two nginx.exe there. This shows that we have already started. As for why, we will not delve into it here.

How to use Nginx as reverse proxy for Tomcat server

Now that we have started nginx, we can start tomcat. If we want to directly access http://localhost, we can directly access tomcat. Don't worry, let's take a look at what nginx looks like after starting. Directly accessing http://localhost can see:

How to use Nginx as reverse proxy for Tomcat server

We can see that nginx started successfully, and now the access is directly into the nginx directory. So where are these actually configured. This involves nginx.conf, an important configuration file of nginx.
2) We can see that there is a conf folder in the nginx folder, which contains several files. Regardless of the others, we open nginx.conf and we can see a paragraph:

How to use Nginx as reverse proxy for Tomcat server

This code is in the server and is equivalent to a proxy server. Of course, multiple ones can be configured. Let's analyze it carefully: listen: Indicates the port that the current proxy server listens to. The default is to listen to port 80. Note that if we configure multiple servers, the listener must be configured differently, otherwise we will not be able to determine where to go. server_name: Indicates where to go after listening. At this time, we go directly to the local area. At this time, it is directly to the nginx folder. location: Indicates the matching path. If / is configured, it means that all requests will be matched here. Root: If root is configured, it means that when the path of this request is matched, the corresponding file will be found in this folder. Here It will be useful for our later static file serving. index: When no home page is specified, the specified file will be selected by default. There can be multiple files and they will be loaded in order. If the first one does not exist, the second one will be found, and so on. The error_page below is the page that represents the error. We will not use it here for the time being, so we will ignore it for now.
Now that we know the specific configuration, how to make it switch to tomcat when accessing localhost. In fact, only two places have been modified:

server_name localhost:8080;  
location / {  proxy_pass http://localhost:8080}

We have modified the above two places. My tomcat is on port 8080, which can be modified according to your own needs. There is a new element proxy_pass here, which represents the proxy path, which is equivalent to forwarding, unlike the root that must be specified before. Now that we have modified the file, does it mean that we must shut down nginx and then restart it? In fact, it is not necessary, nginx can reload the file. We run directly: nginx -s reload
We were too happy, we found an error:

How to use Nginx as reverse proxy for Tomcat server

What did it come from, the error was found on line 45, We didn’t want to find } in that line, so we looked carefully and found that the proxy_pass we added was very strange. It didn’t end with a ; sign. This was the problem. We modified it directly and then ran it again. We found that there was no error and it was ok. If you don't want to load it directly, but just want to see if there are any problems with your configuration file, you can directly enter: nginx -t
This can check whether there are errors in the configuration file. All our modifications below assume that we run nginx -s reload to reload the configuration file after the modification is completed. Please note.
Everything is fine, then we reopen http://localhost and we see the following page:

How to use Nginx as reverse proxy for Tomcat server

这时,我们发现它并不是刚才的welcome页面了,而是tomcat的管理页面了,不管我们点击什么链接都是没问题的,相当于直接访问http://localhost:8080一样。
3)上面我们直接试了一个小例子,让nginx进行转发,即所谓的反向代理。但实际上我们的需求不会是这样的,我们需要分文件类型来进行过滤,比如jsp直接给tomcat处理,因为nginx并不是servlet容器,没办法处理jsp,而html,js,css这些不需要处理的,直接给nginx进行缓存。下面我们来进行一下配置,让jsp页面直接给tomcat,而html,png等一些图片和js等直接给nginx进行缓存。这时最主要用的还是location这个元素,并且涉及到一部分正则,但不难:

location ~ .jsp$ {    proxy_pass http://localhost:8080;}  
location ~ .(html|js|css|png|gif)$ {  root d:/software/developertools/server/apache-tomcat-7.0.8/webapps/root;} 
location ~ .jsp$ {    proxy_pass http://localhost:8080;} 
location ~ .(html|js|css|png|gif)$ {  root d:/software/developertools/server/apache-tomcat-7.0.8/webapps/root;}

  我们先要去掉之前配的location /,避免全部请求被拦截了。然后我们再来看看http://localhost

How to use Nginx as reverse proxy for Tomcat server

当我们不指定jsp页面的时候,它会出现找不到,因为,此时并没有相应的location匹配,所以就会有404错误,这时就跳到了nginx自定义的error页面去了。而当我们用http://localhost/index.jsp去访问时,我们看到了熟悉的页面:

How to use Nginx as reverse proxy for Tomcat server

而且图片那些都显示正常,因为图片是png的,所以直接在tomcat/webapps/root目录下直接查找,当然,如果我们点击manager application how-to这个链接,我们发现:

How to use Nginx as reverse proxy for Tomcat server

它还是找不到,为什么呢?因为这是个html页面,但它并不在root目录下,而是在docs目录下,但当我们匹配html时,我们却到root目录下去找,所以还是找不到这个页面。
一般情况下,如果我们需要用nginx来进行静态文件伺服,一般都会把所有静态文件,html,htm,js,css等都放在同一个文件夹下,这样就不会有tomcat这样的情况了,因为tomcat下的是属于不同的项目,这个我们就没办法了。
3)有些人会说,这些都只会找一台服务器,但如果我们想在一台服务器挂了的时候,自动去找另外一台,这怎么办?这实际上nginx都考虑到了。这时,我们之前用的proxy_pass就有大用途了。我们把之前的第一个例子,即全部都代理的修改一下:最后修改如下:

upstream local_tomcat {  server localhost:8080;}  
server{    location / {      proxy_pass http://local_tomcat;    }  
  ##......其他省略
}  
upstream local_tomcat {  server localhost:8080;} 
server{    location / {      proxy_pass http://local_tomcat;    } 
  #......其他省略
}

  我们在server外添加了一个upstream,而直接在proxy_pass里面直接用http://+upstream的名称来使用。我们还是直接来http://localhost,还是和第一个一样的效果,所有链接都没问题,说明我们配置正确。upstream中的server元素必须要注意,不能加http://,但proxy_pass中必须加。我们刚才说可以在一个服务器挂了的情况下连到另外一个,那怎么弄呢?其实很简单,在upstream中的local_tomcat中配置多一个server。比如我现在弄多一个jetty,端口在9999,所以我们配置如下:

upstream local_tomcat {  server localhost:8080;  server localhost:9999;}  
upstream local_tomcat {  server localhost:8080;  server localhost:9999;}

  此时,我们关闭tomcat,而只开jetty。我们来运行http://localhost看看效果:  我们看到它请求到了jetty的页面,但由于jetty的机制,这时没有显示jetty主页,这个我们先不管。但我们的在一个服务器挂的情况下自动使用另外一个的功能实现了。
但有时我们就不想它挂的时候访问另外一个,而只是希望一个服务器访问的机会比另外一个大,这个可以在server最后加上一个weight=数字来指定,数字越大,表明请求到的机会越大。 

upstream local_tomcat {  server localhost:8080 weight=1;  server localhost:9999 weight=5;}  
upstream local_tomcat {  server localhost:8080 weight=1;  server localhost:9999 weight=5;}

 这时我们给了jetty一个更高的权值,让它更有机会访问到,实际上当我们刷新http://localhost访问的时候发现jetty访问机率大很多,tomcat几乎没机会访问,一般情况下,如果我们必须这样用,不要相关太大,以免一个服务器负载太大。当然,server还有一些其他的元素,比如down表示暂时不用到该服务器等等。

The above is the detailed content of How to use Nginx as reverse proxy for Tomcat server. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX and Apache: Deployment and ConfigurationNGINX and Apache: Deployment and ConfigurationMay 01, 2025 am 12:08 AM

NGINX and Apache each have their own advantages, and the choice depends on the specific needs. 1.NGINX is suitable for high concurrency, with simple deployment, and configuration examples include virtual hosts and reverse proxy. 2. Apache is suitable for complex configurations and is equally simple to deploy. Configuration examples include virtual hosts and URL rewrites.

NGINX Unit's Purpose: Running Web ApplicationsNGINX Unit's Purpose: Running Web ApplicationsApr 30, 2025 am 12:06 AM

The purpose of NGINXUnit is to simplify the deployment and management of web applications. Its advantages include: 1) Supports multiple programming languages, such as Python, PHP, Go, Java and Node.js; 2) Provides dynamic configuration and automatic reloading functions; 3) manages application lifecycle through a unified API; 4) Adopt an asynchronous I/O model to support high concurrency and load balancing.

NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

NGINX vs. Apache: A Look at Their ArchitecturesNGINX vs. Apache: A Look at Their ArchitecturesApr 28, 2025 am 12:13 AM

The main architecture difference between NGINX and Apache is that NGINX adopts event-driven, asynchronous non-blocking model, while Apache uses process or thread model. 1) NGINX efficiently handles high-concurrent connections through event loops and I/O multiplexing mechanisms, suitable for static content and reverse proxy. 2) Apache adopts a multi-process or multi-threaded model, which is highly stable but has high resource consumption, and is suitable for scenarios where rich module expansion is required.

NGINX vs. Apache: Examining the Pros and ConsNGINX vs. Apache: Examining the Pros and ConsApr 27, 2025 am 12:05 AM

NGINX is suitable for handling high concurrent and static content, while Apache is suitable for complex configurations and dynamic content. 1. NGINX efficiently handles concurrent connections, suitable for high-traffic scenarios, but requires additional configuration when processing dynamic content. 2. Apache provides rich modules and flexible configurations, which are suitable for complex needs, but have poor high concurrency performance.

NGINX and Apache: Understanding the Key DifferencesNGINX and Apache: Understanding the Key DifferencesApr 26, 2025 am 12:01 AM

NGINX and Apache each have their own advantages and disadvantages, and the choice should be based on specific needs. 1.NGINX is suitable for high concurrency scenarios because of its asynchronous non-blocking architecture. 2. Apache is suitable for low-concurrency scenarios that require complex configurations, because of its modular design.

NGINX Unit: Key Features and CapabilitiesNGINX Unit: Key Features and CapabilitiesApr 25, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports multiple programming languages ​​and provides functions such as dynamic configuration, zero downtime updates and built-in load balancing. 1. Dynamic configuration: You can modify the configuration without restarting. 2. Multilingual support: compatible with Python, Go, Java, PHP, etc. 3. Zero downtime update: Supports application updates that do not interrupt services. 4. Built-in load balancing: Requests can be distributed to multiple application instances.

NGINX Unit vs. Other Application ServersNGINX Unit vs. Other Application ServersApr 24, 2025 am 12:14 AM

NGINXUnit is better than ApacheTomcat, Gunicorn and Node.js built-in HTTP servers, suitable for multilingual projects and dynamic configuration requirements. 1) Supports multiple programming languages, 2) Provides dynamic configuration reloading, 3) Built-in load balancing function, suitable for projects that require high scalability and reliability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function