Nginx全栈部署与运维实战指南
Nginx 服务器
Nginx 是一款高性能的HTTP和反向代理服务器。在高连接并发的情况下,能够支持高达5万个并发连接数的响应,而内存、CPU等系统资源消耗却非常低,运行非常稳定。
Nginx 部署
# 安装 nginx
[root@controller ~ 11:21:28]# yum -y install nginx
# 启动 nginx
[root@controller ~ 11:21:43]# systemctl enable nginx --now
# 准备主页
[root@controller ~ 11:21:54]# echo hello world > /usr/share/nginx/html/index.html
# 防火墙
[root@controller ~ 11:22:26]# systemctl status firewalld
● firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/usr/lib/systemd/system/firewalld.service; disabled; vendor preset: enabled)
Active: inactive (dead)
Docs: man:firewalld(1)
[root@controller ~ 11:23:18]# curl http://10.1.8.10
hello world
# windows客户端修改 C:\Windows\System32\drivers\etc\hosts
# Linux或Unix修改 /etc/hosts
# 添加如下记录
10.1.8.10 www.gsb.cloud
Nginx 配置
配置结构
Nginx 配置采用层级化、模块化的组织方式,整体是 “全局块 → 核心模块块 → 业务模块块” 的嵌套结构。
1. 全局配置块
作用于 Nginx 整个进程的基础配置,不嵌套在任何块内,是配置文件的 “根级别”。
# 全局配置示例
user nginx; # 运行Nginx的用户/用户组
worker_processes auto; # 工作进程数(核心参数,建议设为CPU核心数)
error_log /var/log/nginx/error.log; # 错误日志路径
pid /run/nginx.pid; # 主进程PID文件路径
include /usr/share/nginx/modules/*.conf; # 加载外部模块配置(全局级引入)
2. 核心模块
Nginx 的核心功能模块 events 块,用于处理网络连接相关配置。
events {
worker_connections 1024; # 每个工作进程的最大并发连接数
use epoll; # 事件驱动模型(epoll是Linux下高性能选择)
multi_accept on; # 允许一个进程一次性接受多个新连接
}
3. 业务模块
处理具体业务的核心配置块,最核心的是 http 块(HTTP/HTTPS 服务),可以包含多个 server 块(虚拟主机)。
# http块:所有HTTP/HTTPS服务的公共配置,可嵌套多个server块
http {
# HTTP全局公共配置
include /etc/nginx/mime.types; # 加载MIME类型映射
default_type application/octet-stream; # 默认响应类型
log_format main '$remote_addr - $remote_user [$time_local] "$request"'; # 日志格式
access_log /var/log/nginx/access.log main; # 访问日志
sendfile on; # 高效文件传输开关
keepalive_timeout 65; # 长连接超时时间
# server块:虚拟主机配置(一个http块可包含多个server)
server {
listen 80; # 监听端口(80=HTTP,443=HTTPS)
server_name localhost; # 域名/IP(可配置多个,用空格分隔)
root /usr/share/nginx/html; # 网站根目录
index index.html;
# location块:URL路径匹配规则(一个server块可包含多个location)
location / {
index index.html index.htm; # 默认首页
try_files $uri $uri/ /index.html; # 路径匹配规则
}
# 错误页面配置
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}
# 第二个虚拟主机(示例)
server {
listen 8080;
server_name test.example.com;
# ... 其他配置
}
}
4. 特殊配置:HTTPS 专属块
如果配置 HTTPS,会在 server 块内增加 SSL 相关配置:
server {
listen 443 ssl; # 监听HTTPS端口并启用SSL
server_name example.com;
# SSL证书配置
ssl_certificate /etc/nginx/cert/server.crt; # 公钥文件
ssl_certificate_key /etc/nginx/cert/server.key; # 私钥文件
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# ... 其他配置(如root、location等)
}
配置加载机制
- include 指令:Nginx 支持通过
include引入外部配置文件,实现模块化管理。- 把不同虚拟主机配置拆到
/etc/nginx/conf.d/*.conf - 把不同代理配置拆到
/etc/nginx/default.d/*.conf
- 把不同虚拟主机配置拆到
- 配置优先级:
- 同层级:后定义的配置覆盖先定义的;
- 不同层级:子级(如 location)覆盖父级(如 server/http);
- location 匹配:精准匹配(
=)> 正则匹配(~/~*)> 普通前缀匹配。
nginx.conf 配置详解
# 更多配置详情参考官方文档:
# * 英文官方文档: http://nginx.org/en/docs/
# * 俄文官方文档: http://nginx.org/ru/docs/
# 指定Nginx工作进程的运行用户为nginx
user nginx;
# 工作进程数,设置为auto时会自动根据CPU核心数调整
worker_processes auto;
# 错误日志文件路径及存储位置
error_log /var/log/nginx/error.log;
# Nginx主进程PID文件路径,用于标识进程ID
pid /run/nginx.pid;
# 加载动态模块,详细说明可查看/usr/share/doc/nginx/README.dynamic文件
include /usr/share/nginx/modules/*.conf;
# 事件模块配置块,用于设置网络连接相关参数
events {
# 每个工作进程的最大并发连接数,默认1024
worker_connections 1024;
}
# HTTP核心模块配置块,包含HTTP服务的主要配置
http {
# 定义访问日志的格式,命名为main
# 日志字段说明:客户端IP - 远程用户 [访问时间] "请求信息" 状态码 发送字节数 "来源页面" "用户代理" "代理IP"
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# 启用访问日志,使用main格式,日志文件存储路径
access_log /var/log/nginx/access.log main;
# 启用高效文件传输模式,减少磁盘I/O和CPU消耗
sendfile on;
# 启用TCP_NOPUSH选项,在发送响应时累积数据后一次性发送,提高网络效率(需配合sendfile使用)
tcp_nopush on;
# 启用TCP_NODELAY选项,禁用Nagle算法,减少数据传输延迟(适用于实时性要求高的场景)
tcp_nodelay on;
# HTTP长连接超时时间,超过65秒无活动则关闭连接
keepalive_timeout 65;
# 文件类型哈希表的最大容量,增大可提高文件类型查找效率
types_hash_max_size 4096;
# 引入MIME类型配置文件,定义不同文件后缀对应的响应类型
include /etc/nginx/mime.types;
# 默认MIME类型,当无法识别文件类型时使用(二进制流格式)
default_type application/octet-stream;
# 加载/etc/nginx/conf.d目录下的所有.conf后缀配置文件(模块化配置)
# 更多说明参考http://nginx.org/en/docs/ngx_core_module.html#include
include /etc/nginx/conf.d/*.conf;
# 虚拟主机配置块(默认HTTP服务)
server {
# 监听IPv4的80端口(HTTP默认端口)
listen 80;
# 监听IPv6的80端口
listen [::]:80;
# 虚拟主机域名,_表示匹配所有未明确指定的域名
server_name _;
# 网站根目录,存放静态资源的路径
root /usr/share/nginx/html;
# 加载默认虚拟主机的额外配置文件(来自/etc/nginx/default.d/*.conf)
include /etc/nginx/default.d/*.conf;
# 配置404错误页面,当请求资源不存在时返回/404.html
error_page 404 /404.html;
# 精确匹配/404.html的访问路径(无额外配置,直接返回文件)
location = /404.html {
}
# 配置500/502/503/504服务器错误页面,返回/50x.html
error_page 500 502 503 504 /50x.html;
# 精确匹配/50x.html的访问路径(无额外配置,直接返回文件)
location = /50x.html {
}
}
# TLS/SSL加密服务配置(默认注释,启用需取消注释并配置证书)
#
# server {
# # 监听IPv4的443端口(HTTPS默认端口),启用SSL和HTTP/2协议
# listen 443 ssl http2;
# # 监听IPv6的443端口,启用SSL和HTTP/2协议
# listen [::]:443 ssl http2;
# # 虚拟主机域名(需替换为实际域名)
# server_name _;
# # 网站根目录(与HTTP服务一致)
# root /usr/share/nginx/html;
#
# # SSL证书文件路径(公钥)
# ssl_certificate "/etc/pki/nginx/server.crt";
# # SSL证书密钥文件路径(私钥,需保密)
# ssl_certificate_key "/etc/pki/nginx/private/server.key";
# # SSL会话缓存配置:共享缓存,名称SSL,大小1MB
# ssl_session_cache shared:SSL:1m;
# # SSL会话超时时间,10分钟内再次连接无需重新握手
# ssl_session_timeout 10m;
# # SSL加密套件,优先选择高强度加密算法,排除aNULL和MD5
# ssl_ciphers HIGH:!aNULL:!MD5;
# # 优先使用服务器端指定的加密套件
# ssl_prefer_server_ciphers on;
#
# # 加载默认虚拟主机的额外配置文件
# include /etc/nginx/default.d/*.conf;
#
# # 404错误页面配置(原配置笔误,应为/404.html,此处保留原注释结构)
# error_page 404 /404.html;
# location = /40x.html {
# }
#
# # 服务器错误页面配置
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# }
# }
}
虚拟主机
同一个 web 服务器提供多个站点。
虚拟主机支持多种方式:
- 主机名
- 端口号
- IP地址(基本不用)
根据名称
# 参考主配置文件/etc/nginx/nginx.conf中server块配置
root@controller ~ 13:59:44]# cp /etc/nginx/nginx.conf /etc/nginx/conf.d/vhost-name.conf
[root@controller ~ 14:00:15]# vim /etc/nginx/conf.d/vhost-name.conf
server {
server_name web1.gsb.cloud;
root /usr/share/nginx/web1;
}
server {
server_name web2.gsb.cloud;
root /usr/share/nginx/web2;
}
[root@controller ~ 14:01:22]# mkdir /usr/share/nginx/web{1,2}
[root@controller ~ 14:02:56]# echo web1.gsb.cloud > /usr/share/nginx/web1/index.html
[root@controller ~ 14:03:09]# echo web2.gsb.cloud > /usr/share/nginx/web2/index.html
[root@controller ~ 14:03:17]# systemctl restart nginx
客户端测试
# 配置名称解析,假设web服务器ip地址为10.1.8.10
10.1.8.10 web1.gsb.cloud
10.1.8.10 web2.gsb.cloud
[root@controller ~ 14:03:24]# curl http://web1.gsb.cloud
web1.gsb.cloud
[root@controller ~ 14:04:14]# curl http://web2.gsb.cloud/
web2.gsb.cloud
提示:清理环境,避免影响后续实验。
[root@controller ~ 14:04:43]# mkdir /etc/nginx/conf.d/vhosts
[root@controller ~ 14:05:16]# mv /etc/nginx/conf.d/vhost-name.conf /etc/nginx/conf.d/vhosts
根据 port
[root@controller conf.d 14:13:03]# vim vhost-name.conf
server {
listen 8081;
server_name www.gsb.cloud;
root /usr/share/nginx/8081;
}
server {
listen 8082;
server_name www.gsb.cloud;
root /usr/share/nginx/8082;
}
[root@controller conf.d 14:14:39]# mkdir /usr/share/nginx/808{1,2}
[root@controller conf.d 14:15:17]# echo 8081 > /usr/share/nginx/8081/index.html
[root@controller conf.d 14:15:30]# echo 8082 > /usr/share/nginx/8082/index.html
[root@controller conf.d 14:15:37]# systemctl restart nginx
客户端测试
# 配置名称解析,假设web服务器ip地址为10.1.8.10
10.1.8.10 www.gsb.cloud
[root@controller conf.d 14:15:45]# curl http://www.gsb.cloud:8081
8081
[root@controller conf.d 14:15:55]# curl http://www.gsb.cloud:8082
8082
提示:清理环境,避免影响后续实验。
配置 SSL/TLS
生成证书
#--1--生成私钥
[root@controller ~ 14:55:57]# mkdir certs && cd certs
[root@controller certs 14:56:12]# openssl genrsa -out www.key 2048
#--2--生成请求文件csr
[root@controller certs 14:56:20]# openssl req -new -key www.key -out www.csr -subj "/C=CN/ST=JS/L=NJ/O=LM/OU=DEVOPS/CN=www.gsb.cloud/emailAddress=webadmin@gsb.cloud"
# CN的值必须是网站域名
#--3--使用自己的私钥对请求文件签名,以生成证书
[root@controller certs 14:56:49]# openssl x509 -req -days 3650 -in www.csr -signkey www.key -out www.crt
Signature ok
subject=/C=CN/ST=JS/L=NJ/O=LM/OU=DEVOPS/CN=www.gsb.cloud/emailAddress=webadmin@gsb.cloud
Getting Private key
配置站点
[root@controller certs 14:57:03]# mkdir /etc/ssl/certs/www.gsb.cloud
[root@controller certs 14:57:22]# mv www* /etc/ssl/certs/www.gsb.cloud
# 参照默认配置修改
[root@controller certs 14:57:34]# vim /etc/nginx/conf.d/vhost-ssl.conf
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.gsb.cloud;
root /usr/share/nginx/html;
# 证书
ssl_certificate "/etc/ssl/certs/www.gsb.cloud/www.crt";
# 私钥
ssl_certificate_key "/etc/ssl/certs/www.gsb.cloud/www.key";
}
[root@controller certs 14:58:56]# systemctl restart nginx
配置HTTP重定向到https
[root@nginx conf.d 15:17:41]# vim vhost-ssl.conf
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name www.gsb.cloud;
root /usr/share/nginx/html;
# 证书
ssl_certificate "/etc/ssl/certs/www.gsb.cloud/www.crt";
# 私钥
ssl_certificate_key "/etc/ssl/certs/www.gsb.cloud/www.key";
}
# 配置HTTP重定向到https
server {
listen 80;
listen [::]:80;
server_name www.gsb.cloud;
root /usr/share/nginx/html;
# 添加重定向
return 301 https://$host$request_uri;
}
[root@www ~]# systemctl restart nginx
# 防火墙设置
[root@www ~]# firewall-cmd --add-service=https --permanent
[root@www ~]# firewall-cmd --reload
# 测试
[root@client ~]# curl http://www.gsb.cloud/
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
# 使用-k指明目标站点不是一个安全站点
[root@nginx conf.d 15:20:00]# curl -k https://www.gsb.cloud
hello world
# 使用-L指明跟随重定向
[root@nginx conf.d 15:19:56]# curl -Lk http://www.gsb.cloud
hello world
申请免费的https证书
Let’s Encrypt 官方推荐使用 ACME 客户端获取证书,其中 Certbot 是最常用的工具,适配 Linux、Windows 等主流系统。
CentOS 7 系统
- 安装 Certbot
[root@www ~]# yum install certbot -y
提示:certbot 依赖 epel仓库。
- 发起证书申请
执行以下命令启动手动 DNS 验证模式,将www.gsb.cloud替换为你的域名:
[root@www ~]# certbot certonly --manual --preferred-challenges dns -d www.gsb.cloud
若需申请泛域名证书(如*.gsb.cloud),可将域名参数改为-d *.gsb.cloud -d gsb.cloud。
[root@www ~]# certbot certonly --manual --preferred-challenges dns -d gsb.cloud -d *.gsb.cloud
提示:这里我采用第二种方式。
- 完成 DNS 验证
[root@www ~]# certbot certonly --manual --preferred-challenges dns -d gsb.cloud -d *.gsb.cloud
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator manual, Installer None
# 输入邮箱地址
Enter email address (used for urgent renewal and security notices)
(Enter 'c' to cancel): mage16196@163.com
Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.6-August-18-2025.pdf. You must agree
in order to register with the ACME server. Do you agree?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 接受服务协议
(Y)es/(N)o: Y
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Would you be willing, once your first certificate is successfully issued, to
share your email address with the Electronic Frontier Foundation, a founding
partner of the Let's Encrypt project and the non-profit organization that
develops Certbot? We'd like to send you email about our work encrypting the web,
EFF news, campaigns, and ways to support digital freedom.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# 同意邮箱接收该组织发来各种信息
(Y)es/(N)o: Y
Account registered.
Requesting a certificate for gsb.cloud and *.gsb.cloud
Performing the following challenges:
dns-01 challenge for gsb.cloud
dns-01 challenge for gsb.cloud
# 根据提示添加第一条 TXT 记录
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Please deploy a DNS TXT record under the name
_acme-challenge.gsb.cloud with the following value:
Oy-tOQmfvcN89A6DXEo-K4S419OFz2AC0HumHHXAgUU
Before continuing, verify the record is deployed.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Press Enter to Continue
# 这里不要按回车,等 TXT 记录配置完成后再按回车
# 这里不要按回车,等 TXT 记录配置完成后再按回车
# 这里不要按回车,等 TXT 记录配置完成后再按回车
登录域名服务商(如阿里云、腾讯云)的 DNS 控制台,添加对应的 TXT 记录。
添加后需要等待一段时间,然后通过以下命令验证记录是否生效,直到能查到该记录,再按回车继续。
[root@linux ~]# nslookup -type=TXT _acme-challenge.gsb.cloud
Server: 223.5.5.5
Address: 223.5.5.5#53
Non-authoritative answer:
_acme-challenge.gsb.cloud text = "Oy-tOQmfvcN89A6DXEo-K4S419OFz2AC0HumHHXAgUU"
Authoritative answers can be found from:
- 根据提示,再次添加一个TXT记录。
Please deploy a DNS TXT record under the name
_acme-challenge.gsb.cloud with the following value:
F_wkFIItFwq0UUuIqSmFR2ZvonK8Hu5r-BdIm388-WE
Before continuing, verify the record is deployed.
(This must be set up in addition to the previous challenges; do not remove,
replace, or undo the previous challenge tasks yet. Note that you might be
asked to create multiple distinct TXT records with the same name. This is
permitted by DNS standards.)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Press Enter to Continue
# 这里不要按回车,等 TXT 记录配置完成后再按回车
# 这里不要按回车,等 TXT 记录配置完成后再按回车
# 这里不要按回车,等 TXT 记录配置完成后再按回车
再次登录域名服务商(如阿里云、腾讯云)的 DNS 控制台,添加新的 TXT 记录。
添加后需要等待一段时间,然后通过以下命令验证记录是否生效,直到能查到该记录,再按回车继续。
[root@linux ~ 10:34:48]# nslookup -type=TXT _acme-challenge.gsb.cloud
Server: 223.5.5.5
Address: 223.5.5.5#53
Non-authoritative answer:
_acme-challenge.gsb.cloud text = "F_wkFIItFwq0UUuIqSmFR2ZvonK8Hu5r-BdIm388-WE"
_acme-challenge.gsb.cloud text = "Oy-tOQmfvcN89A6DXEo-K4S419OFz2AC0HumHHXAgUU"
Authoritative answers can be found from:
- 获取证书
Waiting for verification...
Resetting dropped connection: acme-v02.api.letsencrypt.org
Cleaning up challenges
Subscribe to the EFF mailing list (email: mage16196@163.com).
Starting new HTTPS connection (1): supporters.eff.org
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/gsb.cloud/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/gsb.cloud/privkey.pem
Your certificate will expire on 2026-02-23. To obtain a new or
tweaked version of this certificate in the future, simply run
certbot again. To non-interactively renew *all* of your
certificates, run "certbot renew"
- If you like Certbot, please consider supporting our work by:
Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate
Donating to EFF: https://eff.org/donate-le
验证通过后,证书会自动生成并存储在/etc/letsencrypt/live/你的域名/目录下,包含证书链文件fullchain.pem和私钥文件privkey.pem。
设置自动续期
Let’s Encrypt 证书有效期为 90 天,可通过定时任务实现自动续期。例如 Linux 系统中,添加 crontab 定时任务:
# 每天凌晨2点检查证书,到期自动续期
echo "0 2 * * * /usr/bin/certbot renew --quiet" | tee -a /etc/crontab
证书续期后,网站如何更新证书
推荐解决方案:
- 网站证书通过软连接指向生成的位置。(首选)
- 网站证书直接指向生成的位置。
- 配置监控脚本:证书发生变化后,复制到网站证书位置,并重启网站服务。
配置基本认证
用户名和密码使用plain text发送,所以最好配置SSL/TLS。
# add user for Basic authentication
[root@nginx conf.d 15:51:02]# vim /etc/nginx/conf.d/vhost-ssl.conf
# add into the [server] section
server {
.....
location /auth-basic/ {
auth_basic "Basic Auth";
auth_basic_user_file "/etc/nginx/.htpasswd";
}
}
[root@www ~]# systemctl restart nginx
# 安装工具
[root@nginx conf.d 15:34:13]# yum -y install httpd-tools
[root@nginx conf.d 15:56:06]# htpasswd -b -c /etc/nginx/.htpasswd gsb 123456
Adding password for user gsb
# create a test page
[root@nginx conf.d 15:56:38]# mkdir /usr/share/nginx/html/auth-basic
[root@nginx conf.d 15:58:09]# vim /usr/share/nginx/html/auth-basic/index.html
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: gsber;">
Test Page for Basic Authentication
</div>
</body>
</html>
# 测试,通过-u选项指定用户名和密码
[root@nginx conf.d 16:03:29]# curl -ku gsb:123456 https://www.gsb.cloud/auth-basic/
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: gsber;">
Test Page for Basic Authentication
</div>
</body>
</html>
openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构
更多推荐


所有评论(0)