Nginx全栈部署与运维实战指南
Nginx 服务器Nginx 是一款高性能的HTTP和反向代理服务器。在高连接并发的情况下能够支持高达5万个并发连接数的响应而内存、CPU等系统资源消耗却非常低运行非常稳定。Nginx 部署# 安装 nginx[rootcontroller ~11:21:28]# yum -y install nginx# 启动 nginx[rootcontroller ~11:21:43]# systemctl enable nginx --now# 准备主页[rootcontroller ~11:21:54]# echo hello world /usr/share/nginx/html/index.html# 防火墙[rootcontroller ~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)[rootcontroller ~11:23:18]# curl http://10.1.8.10hello world# windows客户端修改 C:\Windows\System32\drivers\etc\hosts# Linux或Unix修改 /etc/hosts# 添加如下记录10.1.8.10 www.gsb.cloudNginx 配置配置结构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; # 监听端口80HTTP443HTTPS 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{listen443ssl;# 监听HTTPS端口并启用SSLserver_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/httplocation 匹配精准匹配 正则匹配~/~* 普通前缀匹配。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块配置rootcontroller ~13:59:44]# cp /etc/nginx/nginx.conf /etc/nginx/conf.d/vhost-name.conf[rootcontroller ~14:00:15]# vim /etc/nginx/conf.d/vhost-name.confserver{server_name web1.gsb.cloud;root /usr/share/nginx/web1;}server{server_name web2.gsb.cloud;root /usr/share/nginx/web2;}[rootcontroller ~14:01:22]# mkdir /usr/share/nginx/web{1,2}[rootcontroller ~14:02:56]# echo web1.gsb.cloud /usr/share/nginx/web1/index.html[rootcontroller ~14:03:09]# echo web2.gsb.cloud /usr/share/nginx/web2/index.html[rootcontroller ~14:03:17]# systemctl restart nginx客户端测试# 配置名称解析假设web服务器ip地址为10.1.8.1010.1.8.10 web1.gsb.cloud10.1.8.10 web2.gsb.cloud[rootcontroller ~14:03:24]# curl http://web1.gsb.cloudweb1.gsb.cloud[rootcontroller ~14:04:14]# curl http://web2.gsb.cloud/web2.gsb.cloud提示清理环境避免影响后续实验。[rootcontroller ~14:04:43]# mkdir /etc/nginx/conf.d/vhosts[rootcontroller ~14:05:16]# mv /etc/nginx/conf.d/vhost-name.conf /etc/nginx/conf.d/vhosts根据 port[rootcontroller conf.d14:13:03]# vim vhost-name.confserver{listen8081;server_name www.gsb.cloud;root /usr/share/nginx/8081;}server{listen8082;server_name www.gsb.cloud;root /usr/share/nginx/8082;}[rootcontroller conf.d14:14:39]# mkdir /usr/share/nginx/808{1,2}[rootcontroller conf.d14:15:17]# echo 8081 /usr/share/nginx/8081/index.html[rootcontroller conf.d14:15:30]# echo 8082 /usr/share/nginx/8082/index.html[rootcontroller conf.d14:15:37]# systemctl restart nginx客户端测试# 配置名称解析假设web服务器ip地址为10.1.8.1010.1.8.10 www.gsb.cloud[rootcontroller conf.d14:15:45]# curl http://www.gsb.cloud:80818081[rootcontroller conf.d14:15:55]# curl http://www.gsb.cloud:80828082提示清理环境避免影响后续实验。配置 SSL/TLS生成证书#--1--生成私钥[rootcontroller ~14:55:57]# mkdir certs cd certs[rootcontroller certs14:56:12]# openssl genrsa -out www.key 2048#--2--生成请求文件csr[rootcontroller certs14:56:20]# openssl req -new -key www.key -out www.csr -subj /CCN/STJS/LNJ/OLM/OUDEVOPS/CNwww.gsb.cloud/emailAddresswebadmingsb.cloud# CN的值必须是网站域名#--3--使用自己的私钥对请求文件签名以生成证书[rootcontroller certs14:56:49]# openssl x509 -req -days 3650 -in www.csr -signkey www.key -out www.crtSignature oksubject/CCN/STJS/LNJ/OLM/OUDEVOPS/CNwww.gsb.cloud/emailAddresswebadmingsb.cloud Getting Private key配置站点[rootcontroller certs14:57:03]# mkdir /etc/ssl/certs/www.gsb.cloud[rootcontroller certs14:57:22]# mv www* /etc/ssl/certs/www.gsb.cloud# 参照默认配置修改[rootcontroller certs14:57:34]# vim /etc/nginx/conf.d/vhost-ssl.confserver{listen443ssl 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;}[rootcontroller certs14:58:56]# systemctl restart nginx配置HTTP重定向到https[rootnginx conf.d15:17:41]# vim vhost-ssl.confserver{listen443ssl 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重定向到httpsserver{listen80;listen[::]:80;server_name www.gsb.cloud;root /usr/share/nginx/html;# 添加重定向return301https://$host$request_uri;}[rootwww ~]# systemctl restart nginx# 防火墙设置[rootwww ~]# firewall-cmd --add-servicehttps --permanent[rootwww ~]# firewall-cmd --reload# 测试[rootclient ~]# curl http://www.gsb.cloud/htmlheadtitle301Moved Permanently/title/headbodycenterh1301Moved Permanently/h1/centerhrcenternginx/1.20.1/center/body/html# 使用-k指明目标站点不是一个安全站点[rootnginx conf.d15:20:00]# curl -k https://www.gsb.cloudhello world# 使用-L指明跟随重定向[rootnginx conf.d15:19:56]# curl -Lk http://www.gsb.cloudhello world申请免费的https证书Let’s Encrypt 官方推荐使用 ACME 客户端获取证书其中 Certbot 是最常用的工具适配 Linux、Windows 等主流系统。CentOS 7 系统安装 Certbot[rootwww ~]# yum install certbot -y提示certbot 依赖 epel仓库。发起证书申请执行以下命令启动手动 DNS 验证模式将www.gsb.cloud替换为你的域名[rootwww ~]# certbot certonly --manual --preferred-challenges dns -d www.gsb.cloud若需申请泛域名证书如*.gsb.cloud可将域名参数改为-d *.gsb.cloud -d gsb.cloud。[rootwww ~]# certbot certonly --manual --preferred-challenges dns -d gsb.cloud -d *.gsb.cloud提示这里我采用第二种方式。完成 DNS 验证[rootwww ~]# certbot certonly --manual --preferred-challenges dns -d gsb.cloud -d *.gsb.cloudSaving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator manual, Installer None# 输入邮箱地址Enter email address(usedforurgent renewal and security notices)(Entercto cancel): mage16196163.com Starting new HTTPS connection(1): acme-v02.api.letsencrypt.org - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Pleasereadthe Terms of Service at https://letsencrypt.org/documents/LE-SA-v1.6-August-18-2025.pdf. You must agreeinorder 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 Lets Encrypt project and the non-profit organization that develops Certbot? Wed 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 certificateforgsb.cloud and *.gsb.cloud Performing the following challenges: dns-01 challengeforgsb.cloud dns-01 challengeforgsb.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 记录。添加后需要等待一段时间然后通过以下命令验证记录是否生效直到能查到该记录再按回车继续。[rootlinux ~]# nslookup -typeTXT _acme-challenge.gsb.cloudServer:223.5.5.5 Address:223.5.5.5#53Non-authoritative answer: _acme-challenge.gsb.cloud textOy-tOQmfvcN89A6DXEo-K4S419OFz2AC0HumHHXAgUUAuthoritative 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 besetupinaddition to the previous challenges;donot 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 记录。添加后需要等待一段时间然后通过以下命令验证记录是否生效直到能查到该记录再按回车继续。[rootlinux ~10:34:48]# nslookup -typeTXT _acme-challenge.gsb.cloudServer:223.5.5.5 Address:223.5.5.5#53Non-authoritative answer: _acme-challenge.gsb.cloud textF_wkFIItFwq0UUuIqSmFR2ZvonK8Hu5r-BdIm388-WE_acme-challenge.gsb.cloud textOy-tOQmfvcN89A6DXEo-K4S419OFz2AC0HumHHXAgUUAuthoritative answers can be found from:获取证书Waitingforverification... Resetting dropped connection: acme-v02.api.letsencrypt.org Cleaning up challenges Subscribe to the EFF mailing list(email: mage16196163.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 keyfilehas been saved at: /etc/letsencrypt/live/gsb.cloud/privkey.pem Your certificate will expire on2026-02-23. To obtain a new or tweaked version of this certificateinthe future, simply run certbot again. To non-interactively renew *all* of your certificates, runcertbot renew- If you like Certbot, please consider supporting our work by: Donating to ISRG / Lets 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点检查证书到期自动续期echo0 2 * * * /usr/bin/certbot renew --quiet|tee-a/etc/crontab证书续期后网站如何更新证书推荐解决方案网站证书通过软连接指向生成的位置。首选网站证书直接指向生成的位置。配置监控脚本证书发生变化后复制到网站证书位置并重启网站服务。配置基本认证用户名和密码使用plain text发送所以最好配置SSL/TLS。# add user for Basic authentication[rootnginx conf.d15:51:02]# vim /etc/nginx/conf.d/vhost-ssl.conf# add into the [server] sectionserver{..... location /auth-basic/{auth_basicBasic Auth;auth_basic_user_file/etc/nginx/.htpasswd;}}[rootwww ~]# systemctl restart nginx# 安装工具[rootnginx conf.d15:34:13]# yum -y install httpd-tools[rootnginx conf.d15:56:06]# htpasswd -b -c /etc/nginx/.htpasswd gsb 123456Adding passwordforuser gsb# create a test page[rootnginx conf.d15:56:38]# mkdir /usr/share/nginx/html/auth-basic[rootnginx conf.d15:58:09]# vim /usr/share/nginx/html/auth-basic/index.htmlhtmlbodydivstylewidth: 100%; font-size: 40px; font-weight: bold; text-align: gsber;Test PageforBasic Authentication/div/body/html# 测试通过-u选项指定用户名和密码[rootnginx conf.d16:03:29]# curl -ku gsb:123456 https://www.gsb.cloud/auth-basic/htmlbodydivstylewidth: 100%; font-size: 40px; font-weight: bold; text-align: gsber;Test PageforBasic Authentication/div/body/html