1. Nginx简介与版本说明
Nginx(发音为”engine x”)是一款高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器。Nginx由Igor Sysoev开发,以高性能、高并发、低内存占用而闻名。更多学习教程www.fgedu.net.cn。
Nginx可以作为负载均衡器、HTTP缓存、Web服务器和反向代理使用,广泛应用于高流量网站和微服务架构。学习交流加群风哥微信: itpux-com。Nginx采用事件驱动的异步架构,能够处理数万个并发连接。
Nginx核心特性:
– 高并发:单机支持数万并发连接
– 低内存:极低的内存消耗
– 反向代理:支持HTTP、FastCGI、uwsgi、SCGI等协议
– 负载均衡:支持轮询、IP哈希、最少连接等策略
– SSL/TLS:支持HTTPS和双向认证
– 静态文件服务:高效的静态文件处理能力
– 虚拟主机:支持基于域名和端口的虚拟主机
– URL重写:强大的正则表达式重写规则
– 缓存:支持代理缓存和FastCGI缓存
2. Nginx版本选择与下载地址
Nginx提供Mainline(主线)和Stable(稳定)两个版本分支。
Nginx版本状态:
1.29.x Mainline 1.29.7 2026-03-24 主线版本,包含最新特性
1.28.x Stable 1.28.3 2026-03-24 稳定版本,生产推荐
1.26.x Stable 1.26.2 2025-XX-XX 长期支持版本
版本号规则:
– Mainline版本:中间数字为奇数(如1.29.x)
– Stable版本:中间数字为偶数(如1.28.x)
Nginx 1.29.7主要更新:
– 默认代理HTTP版本升级为HTTP/1.1并启用keep-alive
– 修复ngx_http_dav_module缓冲区溢出漏洞
– 修复ngx_http_mp4_module缓冲区溢出漏洞
– 修复邮件会话认证漏洞
– 修复流模块OCSP结果绕过漏洞
官方下载地址:
下载页面:https://nginx.org/en/download.html
官方仓库:https://nginx.org/packages/
源码仓库:https://github.com/nginx/nginx
文档中心:https://docs.nginx.com/
3. Nginx下载方式详解
方式一:源码编译安装(推荐生产环境)
$ cd /fgeudb/software
$ wget https://nginx.org/download/nginx-1.28.3.tar.gz
输出示例如下:
–2026-04-04 10:00:00– https://nginx.org/download/nginx-1.28.3.tar.gz
Resolving nginx.org (nginx.org)… 52.58.199.22
Connecting to nginx.org (nginx.org)|52.58.199.22|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 1234567 (1.2M) [application/octet-stream]
Saving to: ‘nginx-1.28.3.tar.gz’
nginx-1.28.3.tar.gz 100%[======================================================================>] 1.18M 5.2MB/s in 0.2s
2026-04-04 10:00:01 (5.2 MB/s) – ‘nginx-1.28.3.tar.gz’ saved [1234567/1234567]
解压源码包:
$ tar -zxvf nginx-1.28.3.tar.gz -C /fgeudb/nginx/
安装编译依赖:
# yum install -y gcc pcre-devel zlib-devel openssl-devel
或Ubuntu/Debian:
# apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev
方式二:官方仓库安装(推荐)
# yum install -y yum-utils
# cat > /etc/yum.repos.d/nginx.repo << 'EOF' [nginx-stable] name=nginx stable repo baseurl=http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=1 enabled=1 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true [nginx-mainline] name=nginx mainline repo baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/ gpgcheck=1 enabled=0 gpgkey=https://nginx.org/keys/nginx_signing.key module_hotfixes=true EOF 安装Nginx: # yum install -y nginx Ubuntu/Debian安装官方仓库: # apt install -y curl gnupg2 ca-certificates lsb-release ubuntu-keyring # curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor | tee /usr/share/keyrings/nginx-archive-keyring.gpg > /dev/null
# echo “deb [arch=$(dpkg –print-architecture) signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx” | tee /etc/apt/sources.list.d/nginx.list
# apt update
# apt install -y nginx
验证安装:
$ nginx -v
输出示例如下:
nginx version: nginx/1.28.3
方式三:Docker容器部署
$ docker pull nginx:1.28.3
输出示例如下:
1.28.3: Pulling from library/nginx
Digest: sha256:abc123def456…
Status: Downloaded newer image for nginx:1.28.3
启动Nginx容器:
$ docker run –name nginx-web \
-p 80:80 \
-p 443:443 \
-v /fgeudb/nginx/conf:/etc/nginx:ro \
-v /fgeudb/nginx/html:/usr/share/nginx/html:ro \
-v /fgeudb/nginx/logs:/var/log/nginx \
-d nginx:1.28.3
输出示例如下:
abc123def456789…
查看容器状态:
$ docker ps | grep nginx
输出示例如下:
abc123def456 nginx:1.28.3 “/docker-entrypoint.…” 10 seconds ago Up 9 seconds 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp nginx-web
方式四:使用国内镜像加速
$ wget https://mirrors.tuna.tsinghua.edu.cn/nginx/nginx-1.28.3.tar.gz
或使用阿里云镜像:
$ wget https://mirrors.aliyun.com/nginx/nginx-1.28.3.tar.gz
输出示例如下:
–2026-04-04 10:01:00– https://mirrors.tuna.tsinghua.edu.cn/nginx/nginx-1.28.3.tar.gz
Resolving mirrors.tuna.tsinghua.edu.cn… 101.6.15.130
Connecting to mirrors.tuna.tsinghua.edu.cn|101.6.15.130|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 1234567 (1.2M) [application/octet-stream]
Saving to: ‘nginx-1.28.3.tar.gz’
nginx-1.28.3.tar.gz 100%[======================================================================>] 1.18M 25.3MB/s in 0.05s
4. Nginx安装部署实战
步骤1:编译安装Nginx
# groupadd nginx
# useradd -g nginx -s /sbin/nologin -M nginx
配置编译选项:
$ cd /fgeudb/nginx/nginx-1.28.3
$ ./configure \
–prefix=/fgeudb/nginx \
–user=nginx \
–group=nginx \
–with-http_ssl_module \
–with-http_v2_module \
–with-http_realip_module \
–with-http_stub_status_module \
–with-http_gzip_static_module \
–with-http_sub_module \
–with-pcre \
–with-stream \
–with-stream_ssl_module \
–with-stream_realip_module
输出示例如下:
Configuration summary
+ using system PCRE library
+ using system OpenSSL library
+ using system zlib library
nginx path prefix: “/fgeudb/nginx”
nginx binary file: “/fgeudb/nginx/sbin/nginx”
nginx modules path: “/fgeudb/nginx/modules”
nginx configuration prefix: “/fgeudb/nginx/conf”
nginx configuration file: “/fgeudb/nginx/conf/nginx.conf”
nginx pid file: “/fgeudb/nginx/logs/nginx.pid”
nginx error log file: “/fgeudb/nginx/logs/error.log”
nginx http access log file: “/fgeudb/nginx/logs/access.log”
编译安装:
$ make -j$(nproc)
# make install
输出示例如下:
make[1]: Leaving directory ‘/fgeudb/nginx/nginx-1.28.3’
步骤2:配置systemd服务
# vi /etc/systemd/system/nginx.service
[Unit]
Description=nginx – high performance web server
Documentation=https://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/fgeudb/nginx/logs/nginx.pid
ExecStartPre=/fgeudb/nginx/sbin/nginx -t -c /fgeudb/nginx/conf/nginx.conf
ExecStart=/fgeudb/nginx/sbin/nginx -c /fgeudb/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
重载服务配置:
# systemctl daemon-reload
启动服务:
# systemctl start nginx
设置开机自启:
# systemctl enable nginx
查看服务状态:
# systemctl status nginx
输出示例如下:
● nginx.service – nginx – high performance web server
Loaded: loaded (/etc/systemd/system/nginx.service; enabled)
Active: active (running) since Fri 2026-04-04 10:05:00 CST; 10s ago
Main PID: 12345 (nginx)
CGroup: /system.slice/nginx.service
├─12345 nginx: master process /fgeudb/nginx/sbin/nginx
└─12346 nginx: worker process
5. Nginx生产环境配置优化
步骤1:配置nginx.conf主配置文件
# vi /fgeudb/nginx/conf/nginx.conf
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
error_log /fgeudb/nginx/logs/error.log warn;
pid /fgeudb/nginx/logs/nginx.pid;
events {
use epoll;
worker_connections 65535;
multi_accept on;
}
http {
include mime.types;
default_type application/octet-stream;
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
client_max_body_size 100m;
client_body_buffer_size 128k;
client_header_buffer_size 4k;
large_client_header_buffers 4 16k;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain text/css text/javascript application/json application/javascript application/xml;
gzip_vary on;
log_format main ‘$remote_addr – $remote_user [$time_local] “$request” ‘
‘$status $body_bytes_sent “$http_referer” ‘
‘”$http_user_agent” “$http_x_forwarded_for” ‘
‘rt=$request_time uct=”$upstream_connect_time” ‘
‘uht=”$upstream_header_time” urt=”$upstream_response_time”‘;
access_log /fgeudb/nginx/logs/access.log main buffer=32k flush=5s;
include /fgeudb/nginx/conf/conf.d/*.conf;
}
步骤2:配置Worker进程优化
worker_processes auto; 自动检测CPU核心数
worker_rlimit_nofile 65535; 每个Worker最大打开文件数
worker_connections 65535; 每个Worker最大连接数
Events配置:
use epoll; 使用epoll事件模型(Linux)
multi_accept on; 一次接受所有新连接
accept_mutex off; 关闭accept互斥锁(高并发场景)
系统内核参数优化:
# vi /etc/sysctl.conf
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.ip_local_port_range = 1024 65535
使配置生效:
# sysctl -p
步骤3:配置连接超时和缓冲
send_timeout 60; 响应客户端超时时间
keepalive_timeout 65; 长连接超时时间
client_body_timeout 60; 请求体超时时间
client_header_timeout 60; 请求头超时时间
缓冲配置:
client_body_buffer_size 128k; 请求体缓冲区大小
client_header_buffer_size 4k; 请求头缓冲区大小
large_client_header_buffers 4 16k; 大请求头缓冲区
output_buffers 1 32k; 输出缓冲区
postpone_output 1460; 发送缓冲区大小
FastCGI缓冲配置:
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
6. Nginx反向代理配置
配置HTTP反向代理
# vi /fgeudb/nginx/conf/conf.d/proxy.conf
upstream backend_servers {
server 192.168.1.51:8080 weight=3;
server 192.168.1.52:8080 weight=2;
server 192.168.1.53:8080 weight=1;
keepalive 32;
}
server {
listen 80;
server_name www.fgedu.net.cn fgedu.net.cn;
access_log /fgeudb/nginx/logs/proxy_access.log main;
error_log /fgeudb/nginx/logs/proxy_error.log;
location / {
proxy_pass http://backend_servers;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection “”;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 32k;
proxy_busy_buffers_size 64k;
}
location /nginx_status {
stub_status on;
access_log off;
allow 192.168.1.0/24;
deny all;
}
}
配置WebSocket代理
server {
listen 80;
server_name ws.fgedu.net.cn;
location /ws {
proxy_pass http://192.168.1.51:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 60s;
proxy_send_timeout 3600s;
proxy_read_timeout 3600s;
}
}
7. Nginx负载均衡配置
负载均衡策略配置
upstream backend {
server 192.168.1.51:8080;
server 192.168.1.52:8080;
server 192.168.1.53:8080;
}
加权轮询:
upstream backend {
server 192.168.1.51:8080 weight=5;
server 192.168.1.52:8080 weight=3;
server 192.168.1.53:8080 weight=2;
}
IP哈希:
upstream backend {
ip_hash;
server 192.168.1.51:8080;
server 192.168.1.52:8080;
server 192.168.1.53:8080;
}
最少连接:
upstream backend {
least_conn;
server 192.168.1.51:8080;
server 192.168.1.52:8080;
server 192.168.1.53:8080;
}
一致性哈希:
upstream backend {
hash $request_uri consistent;
server 192.168.1.51:8080;
server 192.168.1.52:8080;
server 192.168.1.53:8080;
}
健康检查配置
upstream backend {
server 192.168.1.51:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.52:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.53:8080 max_fails=3 fail_timeout=30s backup;
}
参数说明:
– max_fails:最大失败次数,超过后标记为不可用
– fail_timeout:失败超时时间,超过后重新尝试
– backup:备用服务器,其他服务器不可用时启用
– down:标记服务器为不可用
主动健康检查(需要nginx-plus或第三方模块):
upstream backend {
zone backend 64k;
server 192.168.1.51:8080;
server 192.168.1.52:8080;
}
match server_ok {
status 200-399;
header Content-Type = text/html;
body !~ “error”;
}
server {
location / {
proxy_pass http://backend;
health_check interval=5s fails=3 passes=2 match=server_ok;
}
}
8. Nginx SSL/HTTPS配置
步骤1:生成SSL证书
$ openssl genrsa -out /fgeudb/nginx/ssl/fgedu.key 2048
$ openssl req -new -key /fgeudb/nginx/ssl/fgedu.key -out /fgeudb/nginx/ssl/fgedu.csr \
-subj “/C=CN/ST=Beijing/L=Beijing/O=/CN=fgedu.net.cn”
生成自签名证书(测试用):
$ openssl x509 -req -days 365 -in /fgeudb/nginx/ssl/fgedu.csr \
-signkey /fgeudb/nginx/ssl/fgedu.key -out /fgeudb/nginx/ssl/fgedu.crt
输出示例如下:
Signature ok
subject=C=CN, ST=Beijing, L=Beijing, O=, CN=fgedu.net.cn
Getting Private key
生成DH参数:
$ openssl dhparam -out /fgeudb/nginx/ssl/dhparam.pem 2048
输出示例如下:
Generating DH parameters, 2048 bit long safe prime
…++*++*
DH parameters appear ok.
步骤2:配置HTTPS服务器
# vi /fgeudb/nginx/conf/conf.d/ssl.conf
server {
listen 80;
server_name www.fgedu.net.cn fgedu.net.cn;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name www.fgedu.net.cn fgedu.net.cn;
ssl_certificate /fgeudb/nginx/ssl/fgedu.crt;
ssl_certificate_key /fgeudb/nginx/ssl/fgedu.key;
ssl_dhparam /fgeudb/nginx/ssl/dhparam.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security “max-age=31536000; includeSubDomains” always;
add_header X-Frame-Options SAMEORIGIN always;
add_header X-Content-Type-Options nosniff always;
add_header X-XSS-Protection “1; mode=block” always;
access_log /fgeudb/nginx/logs/ssl_access.log main;
error_log /fgeudb/nginx/logs/ssl_error.log;
location / {
proxy_pass http://192.168.1.51:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
}
9. 安装验证与测试
查看Nginx状态
$ ps -ef | grep nginx
输出示例如下:
nginx 12345 1 0 10:05 ? 00:00:00 nginx: master process /fgeudb/nginx/sbin/nginx
nginx 12346 12345 0 10:05 ? 00:00:00 nginx: worker process
查看端口监听:
$ netstat -tlnp | grep nginx
输出示例如下:
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 12345/nginx: master
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 12345/nginx: master
查看Nginx版本和编译参数:
$ nginx -V
输出示例如下:
nginx version: nginx/1.28.3
built by gcc 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04)
built with OpenSSL 3.0.2 15 Mar 2022
TLS SNI support enabled
configure arguments: –prefix=/fgeudb/nginx –user=nginx –group=nginx –with-http_ssl_module –with-http_v2_module …
测试配置文件
$ nginx -t
输出示例如下:
nginx: the configuration file /fgeudb/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /fgeudb/nginx/conf/nginx.conf test is successful
测试并显示配置文件路径:
$ nginx -T
输出示例如下:
nginx: the configuration file /fgeudb/nginx/conf/nginx.conf syntax is ok
# configuration file /fgeudb/nginx/conf/nginx.conf:
user nginx;
worker_processes auto;
…
访问测试
$ curl -I http://192.168.1.51
输出示例如下:
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 04 Apr 2026 10:10:00 GMT
Content-Type: text/html
Content-Length: 615
Last-Modified: Fri, 04 Apr 2026 10:05:00 GMT
Connection: keep-alive
ETag: “662e1234-267”
Accept-Ranges: bytes
测试HTTPS访问:
$ curl -I -k https://192.168.1.51
输出示例如下:
HTTP/2 200
server: nginx
date: Fri, 04 Apr 2026 10:10:00 GMT
content-type: text/html
content-length: 615
last-modified: Fri, 04 Apr 2026 10:05:00 GMT
查看状态页面:
$ curl http://192.168.1.51/nginx_status
输出示例如下:
Active connections: 10
server accepts handled requests
100 100 200
Reading: 0 Writing: 1 Waiting: 9
10. 常见问题与解决方案
问题1:端口被占用
解决方案:
1. 查看端口占用:
$ netstat -tlnp | grep :80
2. 停止占用端口的进程:
# kill -9 $(lsof -t -i:80)
3. 或修改Nginx监听端口:
listen 8080;
问题2:权限不足
解决方案:
1. 检查目录权限:
$ ls -la /fgeudb/nginx/logs/
2. 修改目录所有者:
# chown -R nginx:nginx /fgeudb/nginx/logs/
3. 检查SELinux:
# getenforce
# setenforce 0
# vi /etc/selinux/config
SELINUX=disabled
问题3:Worker连接数不足
解决方案:
1. 查看系统限制:
$ ulimit -n
2. 临时修改:
# ulimit -n 65535
3. 永久修改:
# vi /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
4. 在nginx.conf中设置:
worker_rlimit_nofile 65535;
问题4:配置文件语法错误
解决方案:
1. 测试配置文件:
$ nginx -t
2. 检查括号匹配:
– 确保每个{都有对应的}
– 检查location块是否正确闭合
3. 检查分号:
– 每条指令必须以分号结尾
– 检查是否遗漏分号
4. 使用nginx -T显示完整配置:
$ nginx -T
Nginx服务管理命令
# systemctl start nginx
或
$ /fgeudb/nginx/sbin/nginx
停止服务:
# systemctl stop nginx
或
$ /fgeudb/nginx/sbin/nginx -s stop
优雅停止:
$ /fgeudb/nginx/sbin/nginx -s quit
重载配置:
# systemctl reload nginx
或
$ /fgeudb/nginx/sbin/nginx -s reload
重新打开日志:
$ /fgeudb/nginx/sbin/nginx -s reopen
查看服务状态:
# systemctl status nginx
测试配置:
$ nginx -t
查看帮助:
$ nginx -h
1. 使用Nginx 1.28.x稳定版本;2. 编译安装时选择必要模块;3. 配置合理的Worker进程数和连接数;4. 开启gzip压缩减少传输流量;5. 配置SSL/HTTPS加密传输;6. 使用upstream实现负载均衡;7. 配置健康检查和故障转移;8. 开启访问日志和错误日志;9. 配置系统服务实现自动重启;10. 定期更新版本修复安全漏洞。
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
