跳到主要内容Nginx 安装、参数与反向代理实操笔记 | 极客日志Shell / BashNuct
Nginx 安装、参数与反向代理实操笔记
这篇内容围绕 Nginx 的安装、编译参数、systemd 启动方式、主配置文件结构以及常见模块展开,覆盖了虚拟主机、location 匹配、长连接、Basic 认证、错误页、日志、try_files、状态页、gzip、rewrite、HTTPS、反向代理、FastCGI、memcache 缓存和 IO 模型等实操点。整体更像一份可直接照着改的配置速查与实验笔记,重点放在常用指令、模块依赖和配置取舍上。
Nginx
Nginx 是 Igor Sysoev 开发的轻量级、高性能 HTTP 和反向代理服务器,也能做 IMAP/POP3/SMTP 代理。它从 2004 年发布到现在,靠的不是'功能最多',而是高并发、低内存和稳定性这几项很实在的优势,所以常被放在静态资源服务、反向代理、负载均衡、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. 主配置文件结构
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 处理
}
示例:提高并发处理能力
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 块是最常用的地方,缓存、代理、日志格式、第三方模块,大多都在这里挂。很多人一开始会把所有配置都往这里塞,能跑是能跑,后期排错就很费劲,所以还是得分清楚公共部分和具体站点配置。
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 拼出来的路径会接在它后面。alias 更像路径重映射,写法更灵活,但也更容易把路径映射错,线上问题通常就出在这里。
location 的详细使用
在一个 server 里可以配置多个 location,它们负责把 URI 映射到文件系统或代理目标。
语法规则:location [ = | ~ | ~* | ^~ ] 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 会按顺序检查文件或目录是否存在,找到第一个就直接返回。它比自己写一串 if 稳得多,排障时也更直观。
try_files $uri $uri.html $uri/index.html /errorpage/default.html;
下载服务器
location /download {
root /usr/local/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、set、break、return 这几个指令。
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 平台。它和原生 nginx 的关系有点像'带了扩展生态的发行版',但编译安装前通常得先把现有 nginx 处理干净,不然容易冲突。
IO 模型
IO 模型描述的是操作系统或程序和设备之间的数据传输方式。
同步 / 异步
阻塞 / 非阻塞
五种 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