Article directory
1. Introduction to Nginx
Nginx(“engine x”)是一个高性能的HTTP和反向代理服务器
具有内存占用少,启动极快,高并发能力强的优点、在互联网项目中广泛应用。
一台nginx能承受大约5万个并发连接数。
China Nginx official website: https://www.nginx-cn.net/
GitHub address: https://github.com/nginxinc/
2. Forward agent
代理就是代理服务器介于用户客户端和目标服务器之间,
正向代理就是用户指定想要获取的目标内容,通过客户端先向代理服务器发送请求,再由代理服务器发送到目标服务器,随后将获得的内容返回用户客户端。
正向代理的情况下,客户端需要知道正向代理服务器的IP地址,还有代理程序的端口才可使用。
正向代理是代理用户客户端,为客户端发送请求,使真实的用户客户端对服务器不可见。
3. Reverse proxy
反向代理刚好与正向代理相反。
对于反向代理,客户端对代理是无感知的,
因为客户端不需要任何配置就可以访问,我们只需要将请求发送到反向代理服务器,由反向代理服务器去选择目标服务器获取数据后,在返回给客户端,此时反向代理服务器和目标服务器对外就是一个服务器,
暴露的是代理服务器地址,隐藏了真实服务器IP地址。
If the client wants to access the tomcat server, it only needs to visit www.baidu.com. The real server IP is hidden
4. Example demonstration
1. Reverse proxy example 1 (reverse proxy, visit www.123.com)
Step 1: Modify the host mapping "C:\Windows\System32\drivers\etc\hosts"
Step 2: Modify the configuration file in Nginx and start it
Note 报错
: My nginx and tomcat are both in Docker, and the containers are isolated from each other.
The 8080 port inside the nginx container accessed by 127.0.0.1, and this container does not have tomcat, so an error will definitely be reported. Note
: My tomcat8080 container has been mapped to the 8080 port of the virtual machine, so make the following changes:
You can see the access at this time 成功
but enter www.123.com (hosts port mapping has been set up) but 报错
the solution is: turn off the windows local proxy
and the access is successful.
2. Reverse proxy example 2 (use nginx reverse proxy to jump to services on different ports according to the access path)
Step 1: In order to distinguish Tomcat, make small changes to the welcome page. Modify webapps/ROOT/index.jsp
and do the same for port 8081.
Step 2: Modify the Nginx configuration file and restart Nginx.
Note here:
proxy_pass http://192.168.31.238:8080/;
proxy_pass最后面有斜杠”/”,此时通过浏览器请求http://http://192.168.31.238/edu/,那么实际访问的地址就是 http://192.168.31.238:8080,会将/edu抛弃的,
proxy_pass http://192.168.31.238:8080;
说明:proxy_pass最后面没有斜杠”/”,此时通过浏览器请求http://192.168.31.238/vod/,
那么实际访问的地址就是 http://192.168.31.238/vod/,会将匹配路径/vod一起加过去
注意:路径/usr/share/nginx/html/vod文件夹下需要有html文件才可以正常访问
Step 3: Test results (successful)
5. Location rules of nginx
- = starts with an exact match (highest priority)
- The beginning of ^~ means that the uri starts with a regular string, which can be understood as matching the url path (non-regular)
- ~ starts with a case-sensitive regular match
- ~* starts with case-insensitive regular matching
- !~ and !~* are case-sensitive mismatches and case-insensitive mismatches respectively.
- / Universal matching, any request will be matched
For more location examples, please refer to: Detailed explanation of nginx location