跳到主要内容
极客日志极客日志面向AI+效率的开发者社区
首页博客GitHub 精选镜像工具UI配色美学隐私政策关于联系
搜索内容 / 工具 / 仓库 / 镜像...⌘K搜索
注册
博客列表
Shell / Bash

Nginx 安装配置、核心参数及反向代理实战

Nginx 是一款高性能 HTTP 和反向代理服务器。涵盖源码编译安装、平滑升级回滚、Systemd 配置、核心参数详解(events/http)、基于域名的站点发布、location 匹配规则、长连接、账户认证、自定义错误页、文件检测、下载服务、状态监控、压缩功能、变量使用、Rewrite 重写、HTTPS 加密、防盗链、反向代理(七层/四层/FastCGI)以及 IO 模型原理。适合运维人员学习部署与优化。

竹影清风发布于 2026/4/9更新于 2026/5/2213 浏览

Nginx

Nginx 是一款由俄罗斯程序员 Igor Sysoev 开发的轻量级、高性能的 HTTP 和反向代理服务器,同时也是一个 IMAP/POP3/SMTP 代理服务器。自 2004 年首次发布以来,Nginx 凭借其高并发处理能力、低内存消耗和稳定性,成为全球最受欢迎的 Web 服务器之一,广泛应用于静态资源服务、反向代理、负载均衡、API 网关等场景。

Nginx 安装

源码编译

解压压缩包:

tar zxf nginx-1.24.0.tar.gz
cd nginx-1.24.0

编译与安装:

./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
make
make install

验证版本以及编译参数:

/usr/local/nginx/sbin/nginx -V
查看版本信息
/usr/local/nginx/sbin/nginx -v
自定义版本(在编译前编辑文件)

编辑版本相关文件:

vim src/core/nginx.h
#define NGINX_VERSION ""
#define NGINX_VER "custom/" NGINX_VERSION

平滑升级和回滚

升级

解压并编译新版本:

tar zxf nginx-1.26.1.tar.gz
cd nginx-1.26.1/
./configure --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
make

注意:只要 make 无错误,不需要 make install。

查看两个版本对比。

  1. 把之前的旧版 nginx 命令备份。
  2. 把新版本的 nginx 命令复制过去。
  3. 检测一下有没有问题。
  4. 回收旧版本进程(如需要)。
回滚

如果升级的版本发现问题需要回滚,可以重新拉起旧版本的 worker。

回滚文件:做之前要先备份新版文件 cp nginx nginx.26。

编写 Nginx 启动文件 systemd

搜索模板:systemd site:nginx.org

创建配置文件:

cd /lib/systemd/system
vim nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP 
ExecStop=/bin/kill -s QUIT 
PrivateTmp=

[Install]
WantedBy=multi-user.target
$MAINPID
$MAINPID
true

使编写的配置生效:

systemctl daemon-reload
systemctl enable --now nginx

Nginx 配置文件参数详解

1. Nginx 主配置文件说明

主配置文件结构:四部分

main block: 主配置段,即全局配置段
# 事件驱动相关的配置
event { ... }

# http/https 作为 web 服务器相关配置段
http { ... }

# mail 作为邮件服务器相关配置段
mail { ... }

# stream 反向代理相关配置段
stream { ... }
2. 全局配置块参数

默认打开全局配置参数:

user nginx nginx; # 启动 Nginx 工作进程的用户和组
worker_processes [number | auto]; # 启动 Nginx 工作进程的数量,一般设为和 CPU 核心数相同
worker_cpu_affinity 00000001 00000010 00000100 00001000 | auto ; # 将 worker 进程与 cpu 核数绑定
worker_rlimit_nofile 100000; # 所有 worker 最多打开 100000 个文件描述符
error_log logs/error.log notice; # 错误日志记录配置
pid logs/nginx.pid; # pid 文件保存路径
示例:cpu 与核心绑定示例
worker_processes auto;
worker_cpu_affinity 01 10;

测试:

nginx -t
nginx -s reload
ps aux | grep nginx
ps axo pid,cmd,psr | grep nginx
3. events 块配置参数
events {
    worker_connections 10000; # 单个 worker 工作进程最大并发数
    use epoll; # 使用 epoll 机制来实现高并发
    accept_mutex on; # 同一时刻一个请求访问只激活一个 work 进程处理
    multi_accept on; # 把数据缓存多个到一定程度,同时发送给 worker 处理
}
示例:实现 nginx 高并发配置
worker_rlimit_nofile 100000;
events {
    use epoll;
    worker_connections 10000;
}

修改系统限制:

vim /etc/security/limits.conf
* - nofile 100000
* - noproc 100000
ulimit -n 100000

测试并发:

dnf install httpd-tools -y
ab -n 100000 -c10000 http://172.25.254.100/index.html
4. http 块配置参数

http 块是 Nginx 服务器配置中的重要部分,缓存、代理和日志格式定义等绝大多数功能和第三方模块都可以在这设置。

http {
    include mime.types;
    default_type application/octet-stream;
    
    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 logs/access.log main;
    
    sendfile on;
    keepalive_timeout 65;
    
    server { # web 服务配置 }
    include "/usr/local/nginx/conf.d/*.conf";
}
示例:识别 php 文件为 text/html 类型
default_type text/html;

基于域名的 web 站点发布

mkdir -p /webdata/nginx/czg.org/czg/html
echo czg.czg.org > /webdata/nginx/czg.org/czg/html/index.html
mkdir /usr/local/nginx/conf.d
vim /usr/local/nginx/conf.d/vhosts.conf
server {
    listen 80;
    server_name www.czg.org;
    root /webdata/nginx/czg.org/czg/html/;
}

在主配置中引入:

include "/usr/local/nginx/conf.d/*.conf";

测试:

nginx -t
nginx -s reload
vim /etc/hosts
curl www.czg.org

location 中的 root 与 alias

root:指定 web 的家目录,在定义 location 的时候,文件的绝对路径等于 root+location。 alias:定义路径别名,会把访问的路径重新定义到其指定的路径。

location 的详细使用

在一个 server 中 location 配置段可存在多个,用于实现从 uri 到文件系统的路径映射。

语法规则:location [ = | ~ | ~* | ^~ ] uri { ... }

  • = 用于标准 uri 前,需要请求字串与 uri 精确匹配。
  • ^~ 用于标准 uri 前,表示包含正则表达式,并且匹配以指定的正则表达式开头。
  • ~ 用于标准 uri 前,表示包含正则表达式,并且区分大小写。
  • ~* 用于标准 uri 前,表示包含正则表达式,并且不区分大小写。

优先级从高到低:=, ^~, ~/~*, 不带符号。

示例 - 精准匹配
location = /test {
    return 200 "punct = \n";
}
示例 - 正则前缀匹配
location ^~ /test {
    return 200 "punct = ^~\n";
}

长连接配置

keepalive_timeout timeout [header_timeout]; # 设定保持连接超时时长
keepalive_requests 数字; # 在一次长连接上所允许请求的资源的最大数量

Nginx Web 页面账户认证

由 ngx_http_auth_basic_module 模块提供此功能。

创建加密信息

htpasswd -cmb /usr/local/nginx/.htpasswd czg czg
htpasswd -mb /usr/local/nginx/.htpasswd czr czr

编辑配置文件

location /admin {
    auth_basic "login passwd";
    auth_basic_user_file "/usr/local/nginx/.htpasswd";
}

测试

curl www.czg.org/admin/
curl www.czg.org/admin/ -uczg:czg

自定义错误页面

生成测试错误页面

mkdir /usr/local/nginx/errorpage
echo "Error Page" > /usr/local/nginx/errorpage/errormessage

编辑配置

error_page 404 405 503 502 /error;
location /error {
    alias /usr/local/nginx/errorpage/errormessage;
}

自定义错误日志

access_log logs/czg.org/czg.access;
error_log logs/czg.org/czg.error error;

Nginx 的文件检测

try_files 会按顺序检查文件是否存在,返回第一个找到的文件或文件夹。

try_files $uri $uri.html $uri/index.html /errorpage/default.html;

下载服务器

location /download {
    root /usr/local/nginx;
}

Nginx 的状态页

基于 nginx 模块 ngx_http_stub_status_module 实现。

location /status {
    stub_status;
    auth_basic "status page";
    auth_basic_user_file "/usr/local/nginx/.htpasswd";
    allow 172.25.254.0/24;
    deny all;
}

状态页信息参数:Active connections, accepts, handled, requests, Reading, Writing, Waiting。

Nginx 的压缩功能

依赖模块 ngx_http_gzip_module。

gzip on;
gzip_comp_level 4;
gzip_disable "MSIE [1-6]\.";
gzip_min_length 1024k;
gzip_buffers 32 1024k;
gzip_types text/plain application/javascript text/css application/xml;
gzip_vary on;
gzip_static on;
Nginx 变量使用

常用内置变量:$remote_addr, $args, $host, $request_uri, $server_name 等。

自定义变量
set $name czg;
set $tomcat_port 8080;

Nginx Rewrite 相关功能

利用 ngx_http_rewrite_module 模块解析和处理 rewrite 请求。

if 指令

用于条件匹配判断。

if ( $http_user_agent ~ firefox ) {
    return 200 "test if messages";
}
set 指令
set $testname czg;
break 指令

用于中断当前相同作用域中的其他 Nginx 配置。

return 指令

用于完成对请求的处理,并直接向客户端返回响应状态码。

return 200 "hello world";
全站加密 https

制作 key:

openssl req -newkey rsa:2048 -nodes -sha256 -keyout /usr/local/nginx/certs/czg.org.key -x509 -days 365 -out /usr/local/nginx/certs/czg.org.crt

编辑配置文件:

listen 443 ssl;
ssl_certificate /usr/local/nginx/certs/cgz.org.crt;
ssl_certificate_key /usr/local/nginx/certs/czg.org.key;
判断文件是否存在
if ( !-e $request_filename ) {
    rewrite ^/(.*) /index.html;
}
Nginx 防盗链

基于客户端携带的 referer 实现。

Nginx 反向代理功能

七层反向代理

基于 ngx_http_proxy_module 模块实现。

配置简单的代理
location / {
    proxy_pass http://172.25.254.10:80;
}
实现动静分离
location ~* \.(php|js)$ {
    proxy_pass http://172.25.254.10:80;
}
location / {
    proxy_pass http://172.25.254.20:80;
}

配置缓存加速

proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;
proxy_cache proxycache;
proxy_cache_valid 200 302 301 10m;
四层反向代理

基于 ngx_stream_proxy_module 模块实现。

stream {
    server {
        listen 3306;
        proxy_pass 172.25.254.50:3306;
    }
}
FastCGI

通过 fastcgi 协议将指定的客户端请求转发至 php-fpm 处理。

fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;

php 源码编译安装

./configure --prefix=/usr/local/php --enable-fpm ...
make && make install

配置优化 php

cp php-fpm.conf.default php-fpm.conf
vim php-fpm.conf
Nginx 整合 php
location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi.conf;
}
php 动态扩展模块(php 的缓存模块)

安装 memcache 模块

配置 php 加载 memcache 模块

部署 memcached

php 高速缓存

实现 nginx 直接访问 memcache 需要两个模块:srcache-nginx-module 和 memc-nginx-module。

重新编译 nginx 添加模块

./configure --add-module=/root/memc-nginx-module-0.20 --add-module=/root/srcache-nginx-module-0.33
make

更换二进制文件

cp -p objs/nginx /usr/local/nginx/sbin/

编辑 nginx 整合 memcache

upstream memcache {
    server 127.0.0.1:11211;
    keepalive 512;
}
location /memc {
    internal;
    memc_pass memcache;
}
location ~ \.php$ {
    srcache_fetch GET /memc $key;
    srcache_store PUT /memc $key;
    fastcgi_pass 127.0.0.1:9000;
}
nginx 二次开发版本

OpenResty 是一个基于 Nginx 与 Lua 的高性能 Web 平台。

编译安装 openresty:因为 openresty 与 nginx 冲突,所以编译安装 openresty 前要把 nginx 卸载。

IO 模型

介绍 IO 模型实际上描述的是操作系统(或程序)和设备(如网络、硬盘等)之间数据传输的方式和策略。

同步/异步 同步 (Synchronous): A 调用 B,B 的处理是同步的。 异步 (Asynchronous): A 调用 B,B 的处理是异步的。

阻塞/非阻塞 阻塞 (Blocking): A 一直等着 B 的返回。 非阻塞 (Non-blocking): I/O 操作被调用后立即返回状态值。

五种 I/O 模型

阻塞 IO(最常见的 IO 模型)——同步阻塞 优点:编程简单。缺点:连接利用率不高。

非阻塞 IO——同步非阻塞 优点:实时性较好。缺点:轮询占用 CPU。

多路复用 I/O——同步阻塞 select, poll, epoll 都是 IO 多路复用的机制。

信号驱动 IO——同步非阻塞 优点:避免轮询。缺点:信号处理复杂。

异步 IO——异步非阻塞 优点:完全非阻塞,性能最佳。缺点:操作系统支持不完善。

目录

  1. Nginx
  2. Nginx 安装
  3. 源码编译
  4. 查看版本信息
  5. 自定义版本(在编译前编辑文件)
  6. 平滑升级和回滚
  7. 升级
  8. 回滚
  9. 编写 Nginx 启动文件 systemd
  10. Nginx 配置文件参数详解
  11. 1. Nginx 主配置文件说明
  12. 事件驱动相关的配置
  13. http/https 作为 web 服务器相关配置段
  14. mail 作为邮件服务器相关配置段
  15. stream 反向代理相关配置段
  16. 2. 全局配置块参数
  17. 示例:cpu 与核心绑定示例
  18. 3. events 块配置参数
  19. 示例:实现 nginx 高并发配置
  20. 4. http 块配置参数
  21. 示例:识别 php 文件为 text/html 类型
  22. 基于域名的 web 站点发布
  23. location 中的 root 与 alias
  24. location 的详细使用
  25. 示例 - 精准匹配
  26. 示例 - 正则前缀匹配
  27. 长连接配置
  28. Nginx Web 页面账户认证
  29. 自定义错误页面
  30. 自定义错误日志
  31. Nginx 的文件检测
  32. 下载服务器
  33. Nginx 的状态页
  34. Nginx 的压缩功能
  35. Nginx 变量使用
  36. 自定义变量
  37. Nginx Rewrite 相关功能
  38. if 指令
  39. set 指令
  40. break 指令
  41. return 指令
  42. 全站加密 https
  43. 判断文件是否存在
  44. Nginx 防盗链
  45. Nginx 反向代理功能
  46. 七层反向代理
  47. 配置简单的代理
  48. 实现动静分离
  49. 四层反向代理
  50. FastCGI
  51. Nginx 整合 php
  52. php 动态扩展模块(php 的缓存模块)
  53. php 高速缓存
  54. nginx 二次开发版本
  55. IO 模型
  • 💰 8折买阿里云服务器限时8折了解详情
  • Magick API 一键接入全球大模型注册送1000万token查看
  • 🤖 一键搭建Deepseek满血版了解详情
  • 一键打造专属AI 智能体了解详情
极客日志微信公众号二维码

微信扫一扫,关注极客日志

微信公众号「极客日志V2」,在微信中扫描左侧二维码关注。展示文案:极客日志V2 zeeklog

更多推荐文章

查看全部
  • 微软发布 Phi-3-vision 多模态模型:42 亿参数展现小模型大潜力
  • 2024 年人工智能大模型发展回顾与展望
  • Web 可访问性最佳实践:构建人人可用的前端界面
  • VSCode 中 GitHub Copilot 插件无模型选项的解决方案
  • Windows NVM 使用指南:多版本 Node.js 管理
  • DeepSeek 内容导出 Word 方案:HTML 转换与自动化脚本实践
  • C# 通过 HTTP API 集成 GLM-4.6V-Flash-WEB 模型实战
  • IDEA/WebStorm 切换分支操作指南
  • Vue3 与 TypeScript 前端高频面试题解析
  • Git 远程与本地仓库关联指南(含推送冲突解决方案)
  • Python aesthetic-ascii2 库功能与使用指南
  • C++ 多态详解:虚函数重写、虚表指针与动态绑定原理
  • TCP Socket 网络编程详解:API、多线程与守护进程
  • WorkBuddy:腾讯 AI 办公助手与智能工作流
  • C++ 仿函数核心解析:状态、性能与 STL 实践
  • Gradle 学习系列:如何自定义 Plugin
  • 2026 年免费及低成本 AI 算力渠道指南与 OpenClaw 配置
  • Spring Boot 消息队列与异步通信实战
  • SpringAI 结合 Ollama 本地部署 Deepseek 实现对话机器人
  • 降低 AIGC 率的 Prompt 指令策略与代码实践

相关免费在线工具

  • Base64 字符串编码/解码

    将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online

  • Base64 文件转换器

    将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online

  • Markdown转HTML

    将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online

  • HTML转Markdown

    将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online

  • JSON 压缩

    通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online

  • JSON美化和格式化

    将JSON字符串修饰为友好的可读格式。 在线工具,JSON美化和格式化在线工具,online