项目说明适用系统Ubuntu 24.04 LTS (Noble)Nginx 版本1.30.3稳定版安装方式源码编译安装安装路径/usr/local/nginx运行用户nginx服务管理systemd日志目录/data/logs/nginx站点根目录/data/www/一、系统环境准备1.1 更新系统并安装编译依赖sudoaptupdatesudoaptinstall-ybuild-essential libpcre3-dev zlib1g-dev libssl-dev依赖包用途build-essential提供 gcc、make 等编译工具libpcre3-devPCRE 正则表达式库rewrite 模块依赖zlib1g-devzlib 压缩库gzip 模块依赖libssl-devOpenSSL 库HTTPS/SSL 支持1.2 创建专用运行用户为保障生产环境安全Nginx 应使用专属系统用户运行避免使用root或与其他服务共用账户。sudoadduser--system--group--no-create-home nginx参数说明--system创建系统用户UID 1000--group同时创建同名用户组--no-create-home不创建家目录最小权限原则验证用户创建idnginx# 输出示例uid999(nginx) gid999(nginx) groups999(nginx)二、下载与解压源码2.1 获取 Nginx 源码进入源码存放目录并下载官方稳定版源码包cd/usr/local/srcsudowgethttps://nginx.org/download/nginx-1.30.3.tar.gz2.2 解压并进入源码目录sudotar-zxvfnginx-1.30.3.tar.gzcdnginx-1.30.3三、配置编译选项3.1 执行 configure 配置sudo./configure\--prefix/usr/local/nginx\--usernginx\--groupnginx\--with-http_ssl_module\--with-http_v2_module\--with-http_realip_module\--with-http_stub_status_module\--with-http_gzip_static_module\--with-stream\--with-stream_ssl_module\--with-cc-opt-O2 -fstack-protector-strong -D_FORTIFY_SOURCE23.2 编译参数说明参数说明--prefix/usr/local/nginx指定安装根目录--usernginx --groupnginx指定运行用户和组--with-http_ssl_module启用 HTTPSSSL/TLS支持--with-http_v2_module启用 HTTP/2 协议支持--with-http_realip_module获取客户端真实 IP用于代理场景--with-http_stub_status_module启用状态监控页面--with-http_gzip_static_module支持发送预压缩的静态文件.gz--with-stream启用 TCP/UDP 四层代理功能--with-stream_ssl_module启用四层代理的 SSL/TLS 加密--with-cc-opt安全编译选项栈保护 FORTIFY_SOURCE3.3 验证配置执行后检查输出末尾是否有以下摘要信息Configuration summary using system PCRE library using system zlib library using system OpenSSL library using system threads ...若出现not found错误请检查对应依赖是否已安装。四、编译与安装4.1 执行编译使用所有 CPU 核心并行编译大幅缩短编译时间sudomake-j$(nproc)4.2 执行安装sudomakeinstall4.3 验证安装/usr/local/nginx/sbin/nginx-v# 预期输出nginx version: nginx/1.30.3五、配置 systemd 服务5.1 创建服务单元文件sudovim/etc/systemd/system/nginx.service粘贴以下内容[Unit] DescriptionThe NGINX HTTP and reverse proxy server Afternetwork.target remote-fs.target nss-lookup.target [Service] Typeforking PIDFile/usr/local/nginx/logs/nginx.pid ExecStartPre/usr/local/nginx/sbin/nginx -t ExecStart/usr/local/nginx/sbin/nginx ExecReload/usr/local/nginx/sbin/nginx -s reload ExecStop/bin/kill -s QUIT $MAINPID PrivateTmptrue Restarton-failure RestartSec3s [Install] WantedBymulti-user.target关键配置项说明配置项说明TypeforkingNginx 以守护进程方式运行PIDFile指定 PID 文件路径ExecStartPre启动前测试配置文件语法PrivateTmptrue使用独立临时目录提升安全性Restarton-failure异常退出时自动重启5.2 重载并启动服务sudosystemctl daemon-reloadsudosystemctlenablenginxsudosystemctl start nginxsudosystemctl status nginx5.3 服务管理命令速查操作命令启动sudo systemctl start nginx停止sudo systemctl stop nginx重启sudo systemctl restart nginx重载配置sudo systemctl reload nginx查看状态sudo systemctl status nginx开机自启sudo systemctl enable nginx六、防火墙配置6.1 放行 Web 服务端口sudoufw allow80/tcpsudoufw allow443/tcp6.2 重载并检查规则sudoufw reloadsudoufw status七、创建目录结构并设置权限7.1 创建工作目录# 日志目录sudomkdir-p/data/logs/nginx# 站点根目录示例sudomkdir-p/data/www/default7.2 设置目录所有权和权限# 日志目录所有权归 nginx仅所有者可读写sudochown-Rnginx:nginx /data/logs/nginxsudochmod-R700/data/logs/nginx# 站点目录所有权归 nginx所有者可读写执行其他人可读执行sudochown-Rnginx:nginx /data/www/defaultsudochmod-R755/data/www/default八、生产环境配置8.1 主配置文件nginx.conf编辑主配置文件sudovim/usr/local/nginx/conf/nginx.conf完整配置如下# # 全局配置 # user nginx; worker_processes auto; worker_rlimit_nofile 65535; # # 事件模块 # events { worker_connections 9216; use epoll; multi_accept on; } # # HTTP 模块 # http { # ---------- 基础配置 ---------- include mime.types; default_type application/octet-stream; # ---------- 日志配置JSON 格式 ---------- log_format json_log escapejson { time_local:$time_local, remote_addr:$remote_addr, remote_user:$remote_user, request:$request, status:$status, body_bytes_sent:$body_bytes_sent, request_time:$request_time, http_referrer:$http_referer, http_user_agent:$http_user_agent, http_x_forwarded_for:$http_x_forwarded_for }; access_log /data/logs/nginx/access.log json_log; error_log /data/logs/nginx/error.log warn; # ---------- 安全隐藏版本号 ---------- server_tokens off; # ---------- 安全请求体大小限制 ---------- client_max_body_size 10M; # ---------- 安全超时防护防慢速攻击 ---------- client_header_timeout 8s; client_body_timeout 8s; send_timeout 10s; keepalive_timeout 65; # ---------- DNS 解析器反向代理场景 ---------- resolver 8.8.8.8 114.114.114.114 valid300s; resolver_timeout 5s; # # 限流配置保护后端 PHP/Java 服务 # # 策略1常规 API 限流 # - key: $binary_remote_addr基于客户端 IP # - zone: 20MB 共享内存存储 IP 计数状态 # - rate: 每秒 12 个请求可根据后端处理能力调整 limit_req_zone $binary_remote_addr zoneapi_limit:20m rate12r/s; # 策略2登录接口限流更严格防暴力破解 # - rate: 每分钟 2 个请求r/m requests per minute # - 独立 zone避免消耗 API 限流额度 limit_req_zone $binary_remote_addr zonelogin_limit:10m rate2r/m; # 策略3健康检查接口限流宽松不影响监控 # - rate: 每秒 30 个请求 # - 确保监控系统能正常探测 limit_req_zone $binary_remote_addr zonehealth_limit:5m rate30r/s; # ---------- 安全全局安全响应头 ---------- add_header X-Frame-Options SAMEORIGIN always; add_header X-XSS-Protection 1; modeblock always; add_header X-Content-Type-Options nosniff always; add_header Referrer-Policy strict-origin-when-cross-origin always; add_header Strict-Transport-Security max-age31536000; includeSubDomains always; # ---------- SSL/TLS 安全配置 ---------- ssl_protocols TLSv1.2 TLSv1.3; # 以下指令仅对 TLS 1.2 及以下版本生效TLS 1.3 自动协商 ssl_prefer_server_ciphers on; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; # ---------- Gzip 压缩 ---------- gzip on; gzip_vary on; gzip_min_length 1k; gzip_comp_level 4; gzip_disable msie6; gzip_types text/plain text/css text/xml text/javascript application/json application/javascript application/xmlrss application/rssxml image/svgxml; # ---------- 加载站点配置 ---------- include /usr/local/nginx/conf/conf.d/*.conf; }8.2 创建站点配置目录sudomkdir-p/usr/local/nginx/conf/conf.d8.3 默认站点配置default.confsudovim/usr/local/nginx/conf/conf.d/default.confserver { listen 80; server_name 您的域名; root /data/www/default; index index.html index.htm; # # 限流执行说明重要 # # 限流分为两步 # 1. 在 nginx.conf 的 http 块中用 limit_req_zone 定义规则 # 2. 在 server/location 块中用 limit_req 执行规则 # # 关于 burst 参数 # - 允许瞬间超过 rate 的请求数量上限 # - 相当于一个缓冲池超出 rate 的请求先放入池中 # # 关于 nodelay 参数 # - 不加 nodelay默认缓冲池中的请求排队等待匀速转发 # → 适合后端 API保护 PHP/Java 不被冲垮 # - 加 nodelay缓冲池中的请求立即转发不等待 # → 适合静态资源提升用户体验 # # 生产环境推荐 # - 常规 API不加 nodelay保护后端 # - 登录接口不加 nodelay更严格防刷且用 r/m 单位 # - 健康检查加 nodelay不影响监控 # - 静态资源不加限流或用宽松限流 # # ---------- 常规 API保护后端排队模式 ---------- # rate12r/s, burst24, 无 nodelay # 效果超速请求排队等待约 83ms 放行一个后端压力恒定 location /api/ { limit_req zoneapi_limit burst24; # 如果有后端服务取消注释并配置 # proxy_pass http://127.0.0.1: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; return 200 API response\n; } # ---------- 登录接口更严格防暴力破解 ---------- # rate2r/m, burst5, 无 nodelay # 效果每分钟超过 2 个请求会排队最多排队 5 个 # 适用场景登录、注册、密码重置等敏感接口 location /api/login/ { limit_req zonelogin_limit burst5; # proxy_pass http://127.0.0.1:8080; return 200 Login OK\n; } # ---------- 健康检查接口宽松允许突发 ---------- # rate30r/s, burst50, 加 nodelay # 效果允许瞬间突发大量请求立即返回 # 适用场景K8s 探针、负载均衡健康检查、监控系统 location /api/health/ { limit_req zonehealth_limit burst50 nodelay; access_log off; # proxy_pass http://127.0.0.1:8080; return 200 Healthy\n; } # ---------- 静态资源不限流提升体验 ---------- location /static/ { alias /data/www/static/; expires 30d; access_log off; add_header Cache-Control public, immutable; } # ---------- 禁止访问敏感文件 ---------- location ~* \.(env|git|bak|sql|swp|log|tar|gz|zip|rar|pem|key)$ { deny all; } # ---------- 禁止访问隐藏文件 ---------- location ~ /\. { deny all; } # ---------- 默认请求处理 ---------- location / { try_files $uri $uri/ /index.html; } # ---------- 状态监控仅内网可访问 ---------- location /nginx_status { stub_status; allow 127.0.0.1; allow 192.168.0.0/16; # 根据实际内网网段修改 deny all; } # ---------- 访问日志 ---------- access_log /data/logs/nginx/default_access.log json_log; error_log /data/logs/nginx/default_error.log warn; }8.4 限流配置速查表场景zonerateburstnodelay适用说明常规 APIapi_limit12r/s24❌ 不加保护 PHP/Java 后端匀速处理登录接口login_limit2r/m5❌ 不加防暴力破解极严格健康检查health_limit30r/s50✅ 加保证监控可用允许突发静态资源不限流———直接放行优化缓存8.5 测试配置并重载# 检查配置文件语法sudo/usr/local/nginx/sbin/nginx-t# 重载配置sudosystemctl reload nginx九、日志轮转配置为防止日志文件无限增长导致磁盘空间耗尽需配置 logrotate 进行日志轮转。9.1 创建 logrotate 配置文件sudovim/etc/logrotate.d/nginx内容如下/data/logs/nginx/*.log{daily missingok rotate30compress delaycompress notifempty create644nginx nginx postrotate[-f/usr/local/nginx/logs/nginx.pid]kill-USR1cat/usr/local/nginx/logs/nginx.pidendscript}配置说明参数说明daily每天轮转一次rotate 30保留最近 30 个日志文件compress轮转后压缩gzipdelaycompress延迟到下次轮转时压缩create 644 nginx nginx新建日志文件权限和属主postrotate轮转后通知 Nginx 重新打开日志文件9.2 验证 logrotate 配置sudologrotate-d/etc/logrotate.d/nginx十、验证部署10.1 检查服务状态sudosystemctl status nginx10.2 检查进程psaux|grepnginx预期看到root用户运行的 master 进程nginx用户运行的多个 worker 进程10.3 测试限流效果测试常规 API 限流# 快速发送 30 个请求观察限流效果foriin{1..30};docurl-s-o/dev/null-w%{http_code}\nhttp://localhost/api/;done|sort|uniq-c预期输出示例12 200 # 前 12 个请求正常通过 13 503 # 超出 rateburst 的请求被拒绝12r/s burst24超过36个才会503但这里循环太快实际可能是部分排队部分503测试登录接口限流# 模拟暴力破解尝试快速发送 10 个请求foriin{1..10};docurl-s-o/dev/null-w%{http_code}\nhttp://localhost/api/login/;done|sort|uniq-c预期大量请求返回 503登录接口被严格保护。10.4 测试 HTTP 响应头curl-Ihttp://localhost检查响应中是否包含安全响应头X-Frame-Options、Strict-Transport-Security等以及Server头不显示具体版本号。10.5 查看限流日志# 查看被限流的请求返回 503sudogrep 503 /data/logs/nginx/access.log# 查看 error.log 中的限流日志sudogreplimiting/data/logs/nginx/error.log# 输出示例limiting requests, excess: 5.123 by zone api_limit10.6 浏览器访问在浏览器中访问服务器 IP 地址应看到 Nginx 欢迎页面或您配置的站点首页。十一、安装信息汇总项目路径/值Nginx 版本1.30.3安装根目录/usr/local/nginx可执行文件/usr/local/nginx/sbin/nginx主配置文件/usr/local/nginx/conf/nginx.conf站点配置目录/usr/local/nginx/conf/conf.d/日志目录/data/logs/nginx站点根目录/data/www/default运行用户nginxPID 文件/usr/local/nginx/logs/nginx.pidsystemd 服务/etc/systemd/system/nginx.servicelogrotate 配置/etc/logrotate.d/nginx十二、常用运维命令服务管理sudosystemctl start nginx# 启动sudosystemctl stop nginx# 停止sudosystemctl restart nginx# 重启sudosystemctl reload nginx# 重载配置sudosystemctl status nginx# 查看状态配置管理# 测试配置文件语法sudo/usr/local/nginx/sbin/nginx-t# 查看当前配置sudo/usr/local/nginx/sbin/nginx-T# 查看加载的限流配置sudo/usr/local/nginx/sbin/nginx-T|greplimit_req日志查看# 查看访问日志实时滚动sudotail-f/data/logs/nginx/access.log# 查看错误日志实时滚动sudotail-f/data/logs/nginx/error.log# 查看限流统计被拒绝的请求sudogrep 503 /data/logs/nginx/access.log|wc-l限流参数调优# 如需调整限流参数编辑站点配置sudovim/usr/local/nginx/conf/conf.d/default.conf# 修改 burst 值或添加/删除 nodelay# 测试并重载sudo/usr/local/nginx/sbin/nginx-tsudosystemctl reload nginx十三、版本升级流程当需要升级到新版本时可按以下步骤操作# 1. 备份当前配置sudocp-r/usr/local/nginx/conf /usr/local/nginx/conf.bak# 2. 下载新版本源码cd/usr/local/srcsudowgethttps://nginx.org/download/nginx-x.y.z.tar.gzsudotar-zxvfnginx-x.y.z.tar.gzcdnginx-x.y.z# 3. 使用相同参数配置并编译sudo./configure[与之前完全相同的参数]sudomake-j$(nproc)# 4. 热升级不中断服务sudomakeupgrade附录 A限流配置速查卡A.1 限流指令说明指令位置语法说明limit_req_zonehttplimit_req_zone key zonename:size raterate;定义限流规则存储空间和速率limit_reqserver/locationlimit_req zonename [burstnumber] [nodelay];执行限流引用规则并配置突发策略A.2 速率单位单位含义示例r/s每秒请求数requests per secondrate10r/sr/m每分钟请求数requests per minuterate2r/mA.3 参数决策指南参数作用加/不加适用场景burst突发缓冲池大小✅ 建议加所有限流场景避免瞬间小尖峰被误杀nodelay突发请求立即处理❌ 不加API 接口保护后端数据库连接池nodelay突发请求立即处理✅ 加静态资源、健康检查用户体验优先A.4 生产环境推荐值场景rateburstnodelay说明普通 API10~20r/srate×2❌根据后端压测结果调整登录接口2~5r/m5~10❌严格防暴力破解健康检查30~50r/s50~100✅不影响监控探测静态资源———不限流直接放行A.5 常见问题排查问题现象可能原因解决方法所有请求返回 503rate或burst设置过小增大rate或burst值限流效果不明显rate设置过大未触发限流降低rate值后端服务仍被冲垮使用了nodelay后端压力瞬间过大去掉nodelay让请求排队健康检查被限流健康检查超时后重试触发限流单独为健康检查配置宽松限流或单独 zone附录 B编译参数速查表参数用途生产环境推荐--prefix安装路径✅ 必选--user/--group运行用户/组✅ 必选--with-http_ssl_moduleHTTPS 支持✅ 必选--with-http_v2_moduleHTTP/2 支持✅ 推荐--with-http_realip_module真实 IP 获取✅ 推荐--with-http_stub_status_module状态监控✅ 推荐--with-http_gzip_static_module预压缩静态文件○ 可选--with-streamTCP/UDP 代理○ 按需--with-stream_ssl_module流代理 SSL○ 按需--with-http_v3_moduleHTTP/3 支持○ 按需附录 C故障排查指南问题 1启动失败端口被占用sudonetstat-tlnp|grep:80sudonetstat-tlnp|grep:443找到占用进程并停止或修改 Nginx 监听端口。问题 2限流配置不生效# 检查是否正确加载sudo/usr/local/nginx/sbin/nginx-T|grep-A5limit_req# 检查配置语法sudo/usr/local/nginx/sbin/nginx-t问题 3日志无法写入ls-la/data/logs/nginx确保目录所有者为nginx:nginx权限为700。问题 4配置文件语法错误sudo/usr/local/nginx/sbin/nginx-t错误信息会明确指出问题所在的行号和内容。文档版本2.0适用 Nginx 版本1.30.3最后更新2026-07-12