跳到主要内容Shell / Bash
Nginx 安装配置、核心参数及反向代理实战
Nginx 是一款高性能 HTTP 和反向代理服务器。涵盖源码编译安装、平滑升级回滚、Systemd 配置、核心参数详解(events/http)、基于域名的站点发布、location 匹配规则、长连接、账户认证、自定义错误页、文件检测、下载服务、状态监控、压缩功能、变量使用、Rewrite 重写、HTTPS 加密、防盗链、反向代理(七层/四层/FastCGI)以及 IO 模型原理。适合运维人员学习部署与优化。
竹影清风13 浏览 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
平滑升级和回滚
升级
解压并编译新版本:
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。
查看两个版本对比。
- 把之前的旧版 nginx 命令备份。
- 把新版本的 nginx 命令复制过去。
- 检测一下有没有问题。
- 回收旧版本进程(如需要)。
回滚
如果升级的版本发现问题需要回滚,可以重新拉起旧版本的 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 类型
基于域名的 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 指令
break 指令
用于中断当前相同作用域中的其他 Nginx 配置。
return 指令
用于完成对请求的处理,并直接向客户端返回响应状态码。
return 200 "hello world";
全站加密 https
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 防盗链
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;
./configure --prefix=/usr/local/php --enable-fpm ...
make && make install
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 的缓存模块)
php 高速缓存
实现 nginx 直接访问 memcache 需要两个模块:srcache-nginx-module 和 memc-nginx-module。
./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/
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 操作被调用后立即返回状态值。
阻塞 IO(最常见的 IO 模型)——同步阻塞
优点:编程简单。缺点:连接利用率不高。
非阻塞 IO——同步非阻塞
优点:实时性较好。缺点:轮询占用 CPU。
多路复用 I/O——同步阻塞
select, poll, epoll 都是 IO 多路复用的机制。
信号驱动 IO——同步非阻塞
优点:避免轮询。缺点:信号处理复杂。
异步 IO——异步非阻塞
优点:完全非阻塞,性能最佳。缺点:操作系统支持不完善。
相关免费在线工具
- 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