Nginx的配置文件结构思维导图和常见的使用场景配置示例
先看目录
一、Nginx核心配置文件结构
写的比较好的博客:https://zhuanlan.zhihu.com/p/518538798
二、 Nginx用作反向代理服务器
2.1 场景1 请求全部转发
2.1.1 场景需求
浏览器请求Nginx监听的端口,返回被代理的Tomcat的响应页面。
目前Tomcat端口8080,nginx端口80
2.1.2 修改Nginx配置
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_pass http://localhost:8080;
#root html;
#index index.html index.htm;
}
...省略
}
2.1.3 配置成功效果
2.2 需求2 按照匹配的路径转发
2.2.1 场景需求
Tomcat目前监听两个端口,对应两个Service,需求通过Tomcat代理后,从一个端口访问不同的路径直接对应这两个Tomcat。
Tomcat1 localhost:8080 对应 localhost/abc
Tomcat2 localhost:8081 对应localhost/def
2.2.2 修改Nginx配置
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /abc/ {
proxy_pass http://localhost:8080/;
#root html;
#index index.html index.htm;
}
location /def/ {
proxy_pass http://localhost:8081/;
#root html;
#index index.html index.htm;
}
....省略
}
2.2.3 配置成功效果
2.3 nginx 的location匹配规则
location语法 location [=|~|~*|^~] /uri/ { … }
nginx常用形式
- 正则匹配 location ~ /lagou { }
- 不区分⼤⼩写的正则匹配 location ~* /lagou { }
- 匹配路径的前缀 location ^~ /lagou { }
- 精确匹配 location = /lagou { }
- 普通路径前缀匹配 location /lagou { }
- 优先级:4 > 3 > 2 > 1 > 5
2.4 location以/结尾和不以/结尾的区别
区别:如果以/结尾,则location作为绝对根路径,转发到代理服务时不会把location中匹配的路径部分代理走。如果没有/,则会把匹配的路径部分也给代理走。
举例
location /abc/ {
proxy_pass http://localhost:8080/;
}
上述配置
- 如果访问 http://localhost/abc 相当于访问 http://localhost:8080/
- 如果访问 http://localhost/abc/docs/config/service.html 相当于访问 http://localhost:8080/docs/config/service.html
location /abc {
proxy_pass http://localhost:8080/;
}
上述配置
- 如果访问 http://localhost/abc 相当于访问 http://localhost:8080/abc
- 如果访问 http://localhost/abc/docs/config/service.html 相当于访问 http://localhost:8080/abc/docs/config/service.html
三、Nginx用作负载均衡
3.1 负载均衡的场景举例
3.2 负载均衡配置距离
http {
...省略
#轮询负载均衡配置
upstream abcServer{
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
server {
listen 80;
server_name localhost;
location /abc/ {
proxy_pass http://abcServer/;
}
location /def/ {
proxy_pass http://localhost:8082/;
}
...省略
}
}
3.3 不同的负载均衡策略
3.3.1 默认策略-轮询
轮询策略:每个请求按时间顺序逐⼀分配到不同的服务器,如果某⼀个服务器下线,能⾃动剔除
#轮询负载均衡配置
upstream abcServer{
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
3.3.2 weight 权重策略
权重策略:weight代表权重,默认每⼀个负载的服务器都为1,权重越⾼那么被分配的请求越多(⽤于服务器性能不均衡的场景)
# 权重策略 负载均衡配置
upstream abcServer{
server 127.0.0.1:8080 weight=1;
server 127.0.0.1:8081 weight=2;
}
3.3.3 ip_hash 策略
ip_hash策略:每个请求按照ip的hash结果分配,每⼀个客户端的请求会固定分配到同⼀个⽬标服务器处理,可以解决session问题
# 权重策略 负载均衡配置
upstream abcServer{
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
四、nginx用作静态文件服务器(动静分离)
配置文件举例
location /static/ {
root statcFolder;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!