Nginx 服务器总结:安装、配置、反向代理与负载均衡详解
在 http 块内定义# 默认轮询(round-robin)最少时间(least_time):仅限 Nginx Plus,选择平均延迟最低且活动连接数最少的服务器,可基于header(首字节)或last_byte(完整响应)计算。通用哈希(hash):可指定等作为键值,常用于缓存场景。# consistent 使用一致性哈希✅ Nginx 的安装、启停与基本配置(全局、events、http)。✅
Nginx 服务器总结:安装、配置、反向代理与负载均衡详解
一、Nginx 概述
Nginx 是一款高性能的 HTTP 和反向代理服务器,在高并发连接下能够支持高达 5 万个并发连接,而系统资源消耗却非常低,运行稳定。它采用事件驱动(epoll)的异步非阻塞模型,广泛用于 Web 服务、反向代理、负载均衡、动静分离等场景。
1.1 实验环境规划
| 节点名称 | IP 地址 | 作用 |
|---|---|---|
| nginx-server | 10.1.8.10/24 | Nginx 服务器(用于安装测试) |
| nginx-client | 10.1.8.11/24 | 客户端,用于访问测试 |
二、Nginx 基础部署
2.1 安装 Nginx
# 添加 EPEL 源(CentOS 7 默认源不含 nginx)
[root@nginx-server ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
# 安装 nginx
[root@nginx-server ~]# yum -y install nginx
2.2 启动服务与防火墙
# 启动并设置开机自启
[root@nginx-server ~]# systemctl enable nginx --now
# 自定义默认主页
[root@nginx-server ~]# mv /usr/share/nginx/html/index.html{,.ori} # 备份原主页
[root@nginx-server ~]# echo "Hello world From Nginx" > /usr/share/nginx/html/index.html
# 放行 HTTP 服务(80 端口)
[root@nginx-server ~]# firewall-cmd --add-service=http --permanent
[root@nginx-server ~]# firewall-cmd --reload
2.3 客户端测试
# 在客户端配置 hosts 解析(Linux/Mac)
[root@client ~]# vim /etc/hosts
10.1.8.10 www.laogao.cloud
# 测试访问
[root@client ~]# curl http://www.laogao.cloud
Hello world From Nginx
三、Nginx 配置文件结构详解
Nginx 主配置文件为 /etc/nginx/nginx.conf,采用层级化、模块化的结构,分为 全局块、events 块、http 块(内含 server、location 块)。
3.1 全局配置块
# 运行 Nginx 的工作进程用户(默认 nobody,这里设为 nginx)
user nginx;
# 工作进程数,auto 表示自动匹配 CPU 核心数
worker_processes auto;
# 错误日志路径及级别
error_log /var/log/nginx/error.log warn;
# 主进程 PID 文件
pid /run/nginx.pid;
# 加载动态模块(如第三方模块)
include /usr/share/nginx/modules/*.conf;
3.2 events 块(网络连接相关)
events {
# 每个 worker 进程的最大并发连接数(默认 1024)
worker_connections 1024;
# 使用 epoll 事件模型(Linux 下高性能)
use epoll;
# 允许一个 worker 进程一次性接受多个新连接
multi_accept on;
}
3.3 http 块(HTTP 服务核心配置)
http {
# 引入 MIME 类型映射文件(定义文件后缀与 Content-Type 的对应关系)
include /etc/nginx/mime.types;
# 默认 MIME 类型(当无法识别时,作为二进制流处理)
default_type application/octet-stream;
# 自定义日志格式(main)
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 访问日志路径及使用的格式
access_log /var/log/nginx/access.log main;
# 高效文件传输(减少磁盘 I/O 与 CPU 复制)
sendfile on;
# 累积数据包后一次性发送(需配合 sendfile)
tcp_nopush on;
# 禁用 Nagle 算法,减少延迟
tcp_nodelay on;
# 长连接超时时间(秒)
keepalive_timeout 65;
# 文件类型哈希表大小
types_hash_max_size 4096;
# 加载 /etc/nginx/conf.d/ 下的所有 .conf 文件(模块化配置)
include /etc/nginx/conf.d/*.conf;
# ---------- 虚拟主机 server 块示例 ----------
server {
# 监听 IPv4 和 IPv6 的 80 端口
listen 80;
listen [::]:80;
# 服务器域名(可多个,空格分隔)
server_name www.laogao.cloud;
# 网站根目录
root /usr/share/nginx/html;
# 加载默认虚拟主机的额外配置(如 php 配置)
include /etc/nginx/default.d/*.conf;
# 错误页面配置
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
# 根路径的 location 块
location / {
index index.html index.htm;
}
}
}
四、虚拟主机(Virtual Host)配置实践
Nginx 支持基于 域名、端口 和 IP 的虚拟主机。
4.1 基于域名的虚拟主机
# 创建两个网站的根目录及测试页面
[root@nginx-server ~]# mkdir -p /var/www/web1 /var/www/web2
[root@nginx-server ~]# echo "web1.laogao.cloud" > /var/www/web1/index.html
[root@nginx-server ~]# echo "web2.laogao.cloud" > /var/www/web2/index.html
# 创建配置文件 /etc/nginx/conf.d/vhost-name.conf
[root@nginx-server ~]# vim /etc/nginx/conf.d/vhost-name.conf
# vhost-name.conf
server {
listen 80;
server_name web1.laogao.cloud;
root /var/www/web1;
index index.html;
}
server {
listen 80;
server_name web2.laogao.cloud;
root /var/www/web2;
index index.html;
}
# 重载配置
[root@nginx-server ~]# systemctl reload nginx
客户端测试(需在 hosts 中添加 10.1.8.10 web1.laogao.cloud web2.laogao.cloud):
[root@client ~]# curl http://web1.laogao.cloud
web1.laogao.cloud
[root@client ~]# curl http://web2.laogao.cloud
web2.laogao.cloud
4.2 基于端口的虚拟主机
# 创建不同端口的站点目录
[root@nginx-server ~]# mkdir /usr/share/nginx/808{1,2}
[root@nginx-server ~]# echo 8081 > /usr/share/nginx/8081/index.html
[root@nginx-server ~]# echo 8082 > /usr/share/nginx/8082/index.html
# 配置文件 /etc/nginx/conf.d/vhost-port.conf
[root@nginx-server ~]# vim /etc/nginx/conf.d/vhost-port.conf
server {
listen 8081;
server_name www.laogao.cloud;
root /usr/share/nginx/8081;
}
server {
listen 8082;
server_name www.laogao.cloud;
root /usr/share/nginx/8082;
}
# 重载并测试(注意防火墙需放行对应端口)
[root@nginx-server ~]# systemctl reload nginx
[root@client ~]# curl http://www.laogao.cloud:8081
8081
[root@client ~]# curl http://www.laogao.cloud:8082
8082
五、SSL/TLS 配置(HTTPS)
5.1 生成自签名证书
# 创建证书存放目录
[root@nginx-server ~]# mkdir /etc/ssl/certs/www.laogao.cloud && cd /etc/ssl/certs/www.laogao.cloud
# 1. 生成私钥
[root@nginx-server certs]# openssl genrsa -out www.key 2048
# 2. 生成证书签名请求(CSR),CN 必须与域名一致
[root@nginx-server certs]# openssl req -new -key www.key -out www.csr \
-subj "/C=CN/ST=JS/L=NJ/O=LG/OU=DEVOPS/CN=www.laogao.cloud/emailAddress=webadmin@laogao.cloud"
# 3. 使用私钥自签名生成证书(有效期 10 年)
[root@nginx-server certs]# openssl x509 -req -days 3650 -in www.csr -signkey www.key -out www.crt
5.2 配置 HTTPS 虚拟主机
# 复制默认配置并修改
[root@nginx-server ~]# cp /etc/nginx/nginx.conf /etc/nginx/conf.d/vhost-www-ssl.conf
[root@nginx-server ~]# vim /etc/nginx/conf.d/vhost-www-ssl.conf
# HTTPS 服务(443 端口)
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.laogao.cloud;
root /usr/share/nginx/html;
# 证书与私钥路径
ssl_certificate "/etc/ssl/certs/www.laogao.cloud/www.crt";
ssl_certificate_key "/etc/ssl/certs/www.laogao.cloud/www.key";
# SSL 会话缓存与超时
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
# 加密套件(优先使用高强度算法)
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
}
# HTTP 重定向到 HTTPS(可选)
server {
listen 80;
listen [::]:80;
server_name www.laogao.cloud;
root /usr/share/nginx/html;
return 301 https://$host$request_uri;
}
# 放行 HTTPS 服务(443 端口)
[root@nginx-server ~]# firewall-cmd --add-service=https --permanent
[root@nginx-server ~]# firewall-cmd --reload
# 重载 nginx
[root@nginx-server ~]# systemctl reload nginx
5.3 客户端测试
# -k 忽略证书验证(自签名证书)
[root@client ~]# curl -k https://www.laogao.cloud/
Hello world From Nginx
# -L 跟随重定向(自动从 HTTP 跳转到 HTTPS)
[root@client ~]# curl -Lk http://www.laogao.cloud/
Hello world From Nginx
六、基本认证(Basic Authentication)
# 安装 htpasswd 工具(来自 httpd-tools)
[root@nginx-server ~]# yum install -y httpd-tools
# 创建密码文件(-c 首次创建,-b 非交互式指定密码)
[root@nginx-server ~]# htpasswd -bc /etc/nginx/.htpasswd laogao 123456
# 创建需要认证的目录及测试页
[root@nginx-server ~]# mkdir /usr/share/nginx/html/auth-basic
[root@nginx-server ~]# cat > /usr/share/nginx/html/auth-basic/index.html <<EOF
<html><body><h1>Authenticated Area</h1></body></html>
EOF
在 HTTPS 配置中添加 location 块:
server {
listen 443 ssl http2;
server_name www.laogao.cloud;
root /usr/share/nginx/html;
ssl_certificate ...;
ssl_certificate_key ...;
# 对 /auth-basic/ 路径启用基本认证
location /auth-basic/ {
auth_basic "Basic Auth";
auth_basic_user_file "/etc/nginx/.htpasswd";
}
}
[root@nginx-server ~]# systemctl reload nginx
# 客户端测试(-u 指定用户名密码)
[root@client ~]# curl -ku laogao:123456 https://www.laogao.cloud/auth-basic/
<html><body><h1>Authenticated Area</h1></body></html>
七、PHP 支持(PHP-FPM)
7.1 安装 PHP 及 PHP-FPM
[root@nginx-server ~]# yum install -y php php-fpm php-gd php-common php-pear php-mbstring php-mcrypt
# 启动并设置开机自启
[root@nginx-server ~]# systemctl enable php-fpm --now
# 测试 PHP 解析是否正常
[root@nginx-server ~]# php -r "echo 'Hello PHP';"
Hello PHP
7.2 配置 Nginx 解析 PHP
创建 PHP 测试文件:
[root@nginx-server ~]# echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/info.php
在 HTTPS 的 server 块中添加 location 规则(或单独创建 /etc/nginx/default.d/php.conf):
# 方法一:直接在 server 块中添加
location ~ \.php$ {
# 防止非法路径(如 /xxx.php/yyy)绕过访问控制
try_files $uri =404;
# 将 PHP 请求转发到本地 9000 端口的 PHP-FPM 服务
fastcgi_pass 127.0.0.1:9000;
# 默认索引文件
fastcgi_index index.php;
# 设置要执行的脚本文件绝对路径
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# 引入 FastCGI 默认参数(如 QUERY_STRING, REQUEST_METHOD 等)
include fastcgi_params;
}
# 重载 nginx
[root@nginx-server ~]# systemctl reload nginx
# 客户端测试(访问 info.php)
[root@client ~]# curl -k https://www.laogao.cloud/info.php
# 输出 PHP 系统信息(HTML 格式)
八、反向代理(Reverse Proxy)
8.1 反向代理概念
- 正向代理:代理客户端(隐藏客户端),例如翻墙代理。
- 反向代理:代理服务器(隐藏后端服务器),客户端只看见反向代理服务器。
反向代理的主要作用:
- 负载均衡:分发请求到多个后端服务器。
- 缓存:缓存后端响应,减轻后端压力。
- 动静分离:静态资源由 Nginx 直接处理,动态请求转发到后端应用服务器。
8.2 Location 匹配规则与 proxy_pass
Nginx 使用 location 指令匹配 URL 路径,然后通过 proxy_pass 将请求转发给后端。
Location 优先级(从高到低):
=精确匹配^~前缀匹配(一旦匹配,不再检查正则)~正则匹配(区分大小写) /~*正则匹配(不区分大小写)- 普通前缀匹配(如
/api) /通用匹配
proxy_pass 末尾带 / 与不带 / 的区别:
- 带
/:删除 location 匹配的路径前缀,将剩余部分拼接到后端地址。 - 不带
/:保留 location 匹配的路径前缀,直接拼接到后端地址。
示例:
# 场景1:proxy_pass 末尾带 /
location /api/ {
proxy_pass http://backend:9090/;
}
# 请求 /api/user/list → 后端接收 /user/list
# 场景2:proxy_pass 末尾不带 /
location /api/ {
proxy_pass http://backend:9090;
}
# 请求 /api/user/list → 后端接收 /api/user/list
8.3 反向代理实验环境
搭建三个后端 Web 服务器和一个代理服务器:
| 主机名 | IP 地址 | 角色 |
|---|---|---|
| proxy.laogao.cloud | 10.1.8.20 | 反向代理服务器 |
| nginx1.laogao.cloud | 10.1.8.21 | 后端 Web 服务器 |
| nginx2.laogao.cloud | 10.1.8.22 | 后端 Web 服务器 |
| nginx3.laogao.cloud | 10.1.8.23 | 后端 Web 服务器 |
| client.laogao.cloud | 10.1.8.11 | 客户端测试 |
所有节点安装 nginx,并准备不同的主页内容:
# 在各后端节点执行
[root@nginx1 ~]# echo "welcome to nginx1.laogao.cloud" > /usr/share/nginx/html/index.html
# nginx2、nginx3 类似,内容对应主机名
8.4 代理本地文件(静态资源)
# 在代理服务器上准备不同目录的静态资源
[root@proxy ~]# mkdir -p /var/nginx /var/nginx1 /var/nginx2
[root@proxy ~]# echo "Hello, Nginx" > /var/nginx/index.html
[root@proxy ~]# echo "Hello, Nginx1" > /var/nginx1/index.html
[root@proxy ~]# echo "Hello, Nginx2" > /var/nginx2/index.html
配置文件 /etc/nginx/conf.d/proxy.conf:
server {
listen 80;
server_name www.laogao.cloud;
# 默认根位置
location / {
root /var/nginx;
index index.html;
}
# 普通前缀匹配:/nginx1 映射到 /var/nginx1
location /nginx1 {
root /var; # 实际路径 = /var + /nginx1 = /var/nginx1
index index.html;
}
# 正则匹配:/nginx.* 映射到 /var/www1(优先级高于普通前缀)
location ~ /nginx.* {
root /var/www1;
index index.html;
}
# 精确匹配:仅 /nginx2/index.html 映射到 /var/www2
location = /nginx2/index.html {
root /var/www2;
index index.html;
}
}
优先级测试结果(访问 /nginx1/):
- 正则匹配优先级最高,所以会访问
/var/www1/nginx1/index.html(若存在)。 - 精确匹配只在 URL 完全相等时生效。
8.5 代理远端服务器(反向代理)
server {
listen 80;
server_name www.laogao.cloud;
# 反向代理到后端集群(使用 upstream 或直接写后端地址)
location / {
proxy_pass http://nginx1.laogao.cloud:80/;
# 传递客户端真实信息
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# 代理 /nginx1/ 路径到 nginx1 服务器(注意末尾 / 会剥离路径)
location /nginx1/ {
proxy_pass http://nginx1.laogao.cloud/;
}
# 正则匹配并重写路径后代理
location ~ /nginx[12](.*)$ {
rewrite /nginx[12](.*)$ $1 break;
proxy_pass http://nginx2.laogao.cloud; # 末尾无 /,保留重写后的路径
}
# 精确匹配 + 代理
location = /nginx1/ {
proxy_pass http://nginx1.laogao.cloud/;
}
}
常用 proxy_set_header 说明:
| 指令 | 作用 |
|---|---|
proxy_set_header Host $host; |
传递客户端访问的域名 |
proxy_set_header X-Real-IP $remote_addr; |
传递客户端真实 IP |
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; |
传递代理链路 IP |
proxy_set_header X-Forwarded-Proto $scheme; |
传递原始协议(http/https) |
九、负载均衡(七层)
Nginx 通过 upstream 模块定义后端服务器组,然后在 proxy_pass 中引用该组名,实现负载均衡。
9.1 定义 upstream
# 在 http 块内定义
upstream backends {
# 默认轮询(round-robin)
server nginx1.laogao.cloud:80;
server nginx2.laogao.cloud:80;
server nginx3.laogao.cloud:80;
}
9.2 使用 proxy_pass 引用
server {
listen 80;
server_name www.laogao.cloud;
root /usr/share/nginx/html;
location / {
proxy_pass http://backends/;
# 必要头部
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_redirect off;
}
}
9.3 负载均衡算法及参数
| 算法 | 说明 | 示例 |
|---|---|---|
| 轮询 (rr) | 默认,按顺序轮流分配 | server backend1; |
| 权重轮询 | 按权重比例分配 | server backend1 weight=3; |
| ip_hash | 根据客户端 IP 哈希分配,同一 IP 固定到同一后端 | ip_hash; |
| least_conn | 分配给活动连接数最少的后端 | least_conn; |
| hash | 按自定义键(如 URI)哈希分配 | hash $request_uri; |
常用参数:
upstream backends {
keepalive 32; # 每个 worker 保持的空闲连接数
server nginx1.laogao.cloud:80 weight=5 max_fails=3 fail_timeout=30s;
server nginx2.laogao.cloud:80 weight=2 max_fails=3 fail_timeout=30s;
server nginx3.laogao.cloud:80 backup; # 备份服务器,其他全部故障时启用
server nginx4.laogao.cloud:80 down; # 手动标记为下线
}
9.4 测试负载均衡效果
# 循环访问 90 次,统计各后端出现的次数
[root@client ~]# for n in {1..90}; do curl -s http://www.laogao.cloud/; done | sort | uniq -c
30 welcome to nginx1.laogao.cloud
30 welcome to nginx2.laogao.cloud
30 welcome to nginx3.laogao.cloud
加上权重后(假设权重 10:20:30),测试结果会按比例分配。
十、高级调度算法简介
- 最少时间(least_time):仅限 Nginx Plus,选择平均延迟最低且活动连接数最少的服务器,可基于
header(首字节)或last_byte(完整响应)计算。 - 通用哈希(hash):可指定
$request_uri、$remote_addr$remote_port等作为键值,常用于缓存场景。
upstream backend {
hash $request_uri consistent; # consistent 使用一致性哈希
server backend1:80;
server backend2:80;
}
十一、总结
通过本实验,我们掌握了:
- ✅ Nginx 的安装、启停与基本配置(全局、events、http)。
- ✅ 虚拟主机配置(基于域名、端口)。
- ✅ HTTPS 自签名证书生成及 SSL 配置,HTTP 强制跳转 HTTPS。
- ✅ 基本认证(Basic Auth)增加访问控制。
- ✅ PHP 动态网站支持(Nginx + PHP-FPM)。
- ✅ 反向代理核心:location 匹配优先级、proxy_pass 替换路径规则、常用头部传递。
- ✅ 负载均衡:upstream 定义,多种调度算法(轮询、权重、ip_hash、least_conn 等)。
Nginx 作为高性能 Web 服务器和反向代理,在现代互联网架构中占据核心地位。熟练掌握其配置,能够应对绝大多数 Web 服务的部署、优化及高可用场景。
openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构
更多推荐


所有评论(0)