Nginx
3675字约12分钟
2025-09-23
nginx有master进程和worker进程,master管理多个worker进程,worker进程则是管理用户连接
yum安装
更多详细教程:nginx: Linux packages
安装先决条件:
sudo yum install yum-utils
要设置 yum 存储库,请创建以下内容命名的文件:/etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
默认情况下,使用稳定的 nginx 包的存储库。 如果您想使用主线 nginx 包, 运行以下命令:
sudo yum-config-manager --enable nginx-mainline
要安装 nginx,请运行以下命令:
sudo yum install nginx
当系统提示接受 GPG 密钥时,请验证指纹是否匹配 如果是这样,就接受它。
源码安装
# 安装必要环境
yum install -y gcc pcre pcre-devel zlib zlib-devel openssl openssl-devel
# 下载nginx
wget https://nginx.org/download/nginx-1.26.3.tar.gz
# 创建文件夹
mkdir nginx
# 解压
tar -xzf nginx-1.26.3.tar.gz /nginx
cd nginx/nginx-1.26.3
./configure
# 编译安装
make
make install
# 添加环境变量
vim /etc/profile
# 添加内容
export PATH=$PATH:/usr/local/nginx/sbin/
# 让环境生效
. /etc/profile
nginx语法
# 启动nginx服务
nginx
# 停止nginx服务
nginx -s stop
# 验证nginx.conf语法是否正确
nginx -t
# 重新加载nginx配置文件
nginx -s reload
nginx信号
[root@hadoop01 logs]# ps -ef | grep nginx
UID PID PPID C STIME TTY TIME CMD
# master 父进程
root 34688 1 0 15:11 ? 00:00:00 nginx: master process nginx
# worker 子进程
nobody 34689 34688 0 15:11 ? 00:00:00 nginx: worker process
信号 | 作用 |
---|---|
term /int | 不管有没有请求,立即关闭nginx服务(master和worker服务) |
quit | 把当前请求处理完,在关闭nginx服务(master和worker服务) |
hup | 在不重启nginx的情况下重新读取nginx配置文件 |
usr1 | 日志切割,将日志分为多分,避免日志文件过大 |
usr2 | 平滑升级nginx |
winch | 所有子进程不在接收新请求,且把当前请求处理完,在关闭worker子服务 |
# 使用方法
kill -quit 34688(masterPID)
winch
[root@hadoop01 logs]# ps -ef | grep nginx
root 34688 1 0 15:11 ? 00:00:00 nginx: master process nginx
nobody 42717 34688 0 17:19 ? 00:00:00 nginx: worker process
root 42803 103651 0 17:20 pts/1 00:00:00 grep --color=auto nginx
[root@hadoop01 logs]# kill -winch 34688
[root@hadoop01 logs]# ps -ef | grep nginx
root 34688 1 0 15:11 ? 00:00:00 nginx: master process nginx
root 42897 103651 0 17:21 pts/1 00:00:00 grep --color=auto nginx
系统环境
编辑 vim /usr/lib/systemd/system/nginx.service
,添加如下内容
[Unit]
Description=nginx web service
Documentation=http://nginx.org/en/docs/
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=default.target
设置权限 chmod 755 /usr/lib/systemd/system/nginx.service
重新加载 systemctl
:systemctl daemon-reload
# 启动nginx
systemctl start nginx
# 关闭nginx
systemctl stop nginx
...
nginx不间断升级
将老版本的nginx升级到新版本的nginx,并且服务不能停止
将 nginx-1.24.0 升级到 nginx-1.26.3
编译
nginx-1.26.3
,但不安装cd /nginx-1.26.3 ./configure make
更改老版本的nginx名称
cd /usr/local/nginx/sbin mv nginx nginxold
将新版本的nginx复制到
/usr/local/nginx/sbin
中cd /nginx-1.26.3/objs cp nginx /usr/local/nginx/sbin
执行完上面三个步骤之后
回到上一级目录(也就是安装目录),执行升级命令
cd ..
make upgrade
make upgrade原理
1. 发送usr2,通知老版本 master 进程启动新版本 master 进程
kill -usr2 `more /usr/local/nginx/logs/nginx.pid`
2. 发送quit,通知老版本 master 进程优雅退出,老进程完全退出,由新进程接管所有请求
kill -quit `more /usr/local/nginx/logs/nginx.pid.oldbin`
日志
自定义日志路径
日志
自定义日志路径
# 日志
# 作用:自定义日志的存放路径
# 日志级别:debug|info|notice|warn|error|crit|alert|emerg
# 翻译:测试|信息|通知|警告|错误|临界|警报|紧急
# 建议:不要设置info以下的等级,否则会大量消耗I/O,消耗,影响nginx性能
error_log logs/error.log;
#error_log logs/error.log debug;
#error_log logs/error.log info;
静态资源优化
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
}
压缩
http {
gzip on;
gzip_types text/css;
gzip_comp_level 6;
gzip_vary on;
gzip_min_length 1024;
gzip_disable "msie [1-6]\.";
}
小问题
gzip
和 sendfile
之间相互使用会有冲突,为了解决这个问题,使用下面的指令对文件进行预压缩
http {
# 使用前要先安装模块 --with-http_gzip_static_module
# 说明:允许 Nginx 直接提供预压缩的静态文件(如 .gz 文件)
# 选项:on|off|always(默认off)
# on:判断浏览器是否支持预压缩的静态文件,支持则发送,否则反之
# always:不管浏览器是否支持预压缩的静态文件,都一律发送
# 为了解决 gzip 和 sendfile 之间的冲突问题
gzip_static on;
}
# 进入到项目文件夹中
gzip *.css
# 这样所有的 css 文件都被压缩成 *.css.gz 文件
# 预压缩就完成了
# 验证配置文件是否正确,然后重启nginx
nginx -t
nginx -s reload
添加模块
进入到编译文件夹中
nginx-1.26.3
,但不安装添加
--with-http_gzip_static_module
模块,开启gzip_static
需安装该模块cd /nginx-1.26.3 ./configure --prefix=/usr/local/nginx --with-http_gzip_static_module make
更改nginx名称
cd /usr/local/nginx/sbin mv nginx nginxold
将新版本的nginx复制到
/usr/local/nginx/sbin
中cd /nginx-1.26.3/objs cp nginx /usr/local/nginx/sbin
回到上一级目录(也就是安装目录),执行升级命令
cd .. make upgrade
缓存
expires:
该选项主要是用在老版浏览器上的
http {
include mime.types;
default_type application/octet-stream;
# 控制页面缓存
# 告诉浏览器或客户端如何缓存资源,从而减少重复请求、提升网站性能
# 选项:time|max|epoch|off
# max:等于 10 年
# epoch:等于 no-cache(强制让资源立即过期,禁止客户端缓存该资源)
# off:禁用自动添加缓存相关的响应头,让客户端(如浏览器)根据默认行为或其他自定义头来处理缓存。
# 位置:http|server|location
# d表示天,h表示小时,没有单位则默认表示秒
expires 100d;
# 图片资源缓存1个月
add_header Cache-Control "public, max-age=2592000";
}
cache-control选项:
该选项主要是用在新版浏览器上的
指令 | 类型 | 描述 | 示例 |
---|---|---|---|
max-age=秒数 | 数值型 | 资源在客户端缓存的最大时间(从请求时刻开始计算),到期后需重新验证 | max-age=3600 (1 小时) |
s-maxage=秒数 | 数值型 | 针对共享缓存(如 CDN)的最大缓存时间,优先级高于 max-age | s-maxage=86400 (1 天) |
public | 布尔型 | 资源可被客户端和中间缓存(如代理、CDN)缓存 | Cache-Control: public |
private | 布尔型 | 资源仅限客户端缓存,中间缓存不可存储(通常用于用户私有数据) | Cache-Control: private |
no-cache | 布尔型 | 资源可缓存,但使用前必须向服务器重新验证(需配合 must-revalidate ) | Cache-Control: no-cache |
no-store | 布尔型 | 严格禁止任何形式的缓存,每次请求都必须从服务器获取资源(用于敏感数据) | Cache-Control: no-store |
must-revalidate | 布尔型 | 缓存过期后必须向服务器验证,否则不可使用过期资源 | Cache-Control: must-revalidate |
proxy-revalidate | 布尔型 | 针对代理服务器的重新验证指令,功能类似 must-revalidate ,但仅作用于中间缓存 | Cache-Control: proxy-revalidate |
max-stale=秒数 | 数值型 | 允许使用过期资源的最大时间(秒),到期后必须重新请求 | max-stale=60 (最多使用过期 1 分钟) |
min-fresh=秒数 | 数值型 | 要求资源在指定时间内必须是新鲜的(未过期),否则重新请求 | min-fresh=300 (至少新鲜 5 分钟) |
stale-while-revalidate | 数值型 | 资源过期后,允许客户端继续使用缓存,同时后台异步向服务器验证更新(提升用户体验) | stale-while-revalidate=60 (过期后继续用 1 分钟) |
跨域问题
- 定义:浏览器规定,只有域名、端口、协议完全相同的两个资源之间才能相互访问(即 “同源”)。
- 目的:防止恶意网站窃取用户数据(如 Cookie、LocalStorage 等)
# 80端口默认是不写的,所以同源
http:192.168.1.2/index.html
http:192.168.1.2:80/index.html
# 协议不同,所以不是同源
http:192.168.1.2:8080/index.html
https:192.168.1.2:8080/index.html
实际开发中,当前端页面需要访问非同源的后端资源时,就需要解决跨域问题
location /api {
# 指定允许访问资源的源(Origin),即哪些域名可以跨域请求该资源
# add_header Accept-Control-Allow-Origin *; 表示允所有域名
add_header Accept-Control-Allow-Origin http://192.168.1.2;
# 指定允许的HTTP 请求方法
add_header Accept-Control-Allow_Methods GET,POST,PUT,DELETE;
default_type application/json;
return 200 '{"id":1,"name":"He","age":123}';
}
防盗链
nginx配置文件
非events
和http
块的代码为全局代码
events
块:设置网络配置,主要设置用户与 nginx
之间的网络配置
http
块:设置代理、缓存、日志记录、第三方模块。。。。。。
http
块中可以有多个 server
块
# 指定运行用户
user nobody;
# 工作进程
# 选项:on/off
master_processes on;
# 工作进程数量
# 选项:num/auto
# 使用前提是要开启工作进程 master_processes on;
# 数量越大,处理的并发请求就越多(worker进程也就越多)
# 建议数量值与服务器cpu核数一致
worker_processes 1;
# 守护进程
# 选项:on/off(默认on)
# 开启之后,nginx服务可以在后台运行
daemon on;
# 指定nginx当前master进程的进程号ID存储的文件路径
# 默认路径:/usr/local/nginx/logs/nginx.pid
pid logs/nginx.pid;
# 日志
# 作用:自定义日志的存放路径
# 日志级别:debug|info|notice|warn|error|crit|alert|emerg
# 翻译:测试|信息|通知|警告|错误|临界|警报|紧急
# 建议:不要设置info以下的等级,否则会大量消耗I/O,消耗,影响nginx性能
error_log logs/error.log;
#error_log logs/error.log debug;
#error_log logs/error.log info;
# 引入其他路径的配置文件,使配置更灵活
# 引入的配置文件会生效
include /home/main.conf;
events {
# 选项:on|off(默认on)
# 因为nginx后台是多线程工作的,当客服端发送一个连接时,则会有多个worker进程被唤醒
# 为了避免不必要的浪费,设置accept_mutex on;
# 该选项对nginx进程接收的连接进行序列号处理,然后一个个唤醒接收,防止多个进程对连接的争抢
# 当有多个请求的时候,启用该选项则会导致访问速度变慢
# 所以更具生产环境来决定是否开启
accept_mutex on;
# 多个网络连接
# 选项:on|off(默认on)
# 允许worker进程接收多个连接
multi_accept on;
# 最大连接数
# 选项:num
# 单个worker进程最大连接数
# 建议:不要超过操作系统支持打开的最大文件句柄数量
worker_connections 1024;
# 事件处理模型
# 选项:select|poll|epoll|kqueue
# 建议:选择poll|epoll
# 选择对应的驱动来处理网络信息(epoll效率高一些)
# 根据系统自动选择,Linux 默认为 epoll,BSD 为 kqueue,Windows 为 select。
use epoll;
}
http {
include mime.types;
# 使用范围:http 、server 、location
# 配置nginx响应请求资源类型
# application/octet-stream:当浏览器接收到请求时,会以下载附件的方式来进行下载操作
# text/html:以html格式显示
# text/plain:以文本格式显示
# application/json:显示json
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;
# 日志:访问日志(access.log),错误日志(error.log)
# 自定义访问日志文件路径
# 使用范围:http 、server 、location
access_log /usr/local/nginx/logs/my.log;
# 用于加速静态文件传输(如图片、CSS、JS)
# 选项:on|off
# 使用范围:http 、server 、location
# 零拷贝传输优化
sendfile on;
# 选项:on|off(默认off)
# 前提:sendfile要在开启的状态下才能使用才指令
# 相当于一个缓存空间
# 作用:用来提升网络包传输效率的
# 与 sendfile 配合,将多个小文件合并为一个 TCP 包发送,减少网络包数量。
tcp_nopush on;
# 选项:on|off(默认on)
# 前提:长链接 要在开启的状态下才能使用才指令
# 作用:提高网络包传输的实时性
# 禁用 Nagle 算法,强制立即发送小数据包,降低实时通信延迟。
tcp_nodelay on;
# 长链接的访问时间
# 选项:time
# 每个请求都会重新创建一个连接,为了提升效率
# 让连接的占线时间长一点,这样下一个请求在短时间内就不用重新创建连接了
keepalive_timeout 65;
# 处理100个请求之后就断开连接
keepalive_requests 100;
# 选项:on|off(默认off)
# 压缩文件
gzip on;
# 选项:
# text/plain 纯文本文件(.txt)、日志文件、配置文件等
# text/html 压缩html(默认)
# text/css CSS 样式表文件(.css)
# text/javascript JavaScript 文件(.js,传统格式)
# application/javascript JavaScript 文件(.js,现代 ES6+ 格式)
# application/json JSON 数据(如 API 响应、配置文件)
# application/xml XML 文件(.xml)、RSS 订阅源、SOAP 请求等
# application/x-httpd-php PHP 脚本输出的内容(动态生成的 HTML、JSON 等)
# font/ttf
# font/otf TrueType 和 OpenType 字体文件(.ttf、.otf)
# image/svg+xml SVG 矢量图(文本格式,非二进制)
# application/font-woff
# application/font-woff2
# application/x-font-ttf
# * 压缩所有文件
gzip_types text/css;
# 压缩级别(1-9),6 为平衡值
# 取值 1-9,值越大压缩率越高,但 CPU 消耗也越大。
# 推荐值为 6(平衡压缩率和性能),对性能敏感的场景可设为 4。
gzip_comp_level 6;
# 会在响应头中添加 Vary: Accept-Encoding
# 告知缓存服务器(如 CDN)该内容有压缩和非压缩两个版本,避免缓存混乱。
gzip_vary on; # 增加 Vary: Accept-Encoding 响应头
# 仅压缩大于 1KB 的内容
# 单位:k | m
gzip_min_length 1024;
# 当遇到 IE1~6 时禁用压缩功能
gzip_disable "msie [1-6]\.";
server {
listen 8080;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
# http://192.168.205.207:8080/html/
# 访问项目中的html文件
location /html {
# 项目文件存放位置
root /usr/local/nginx/;
# 设置默认网页首页
index index.html index.htm;
}
# 404页面
error_page 404 /404.html;
location = /404.html {
root html;
index 404.html;
}
# 404页面
# @指向
error_page 404 @404;
location @404 {
default_type text/plain;
return 404 '404...';
}
# 更改状态码
error_page 404 =200 /404.html;
location = /404.html {
root html;
index 404.html;
}
# redirect server error pages to the static page /50x.html
# 错误码,遇到对应的错误时,则跳转到该页面
# 重定向
error_page 500 502 503 504 404 /50x.html;
location = /50x.html {
root html;
}
}
}
server_name
通配符
这样只要有nginx521.cn
和www.nginx123
就可以访问nginx页面了
server_name *.nginx521.cn www.nginx123.*
server_name
访问优先级:精确(www.nginx521.cn
)> default_server
> 通配符(www.nginx123.*
) > 正则表达式
location
# http://192.168.205.207/html 正常
# http://192.168.205.207/html/index.html 正常
location /html {
root /usr/local/nginx/;
index index.html index.htm;
}
# http://192.168.205.207/html 正常
# http://192.168.205.207/html/index.html 404
# 要求访问路径必须和 = 后面的一致
location =/html {
root /usr/local/nginx/;
index index.html index.htm;
}
location
访问优先级:通配符 > 正则表达式 > 精确值(/html
)
# 访问模式:root路径 + location路径
# 相当于访问 /usr/local/nginx/html
location /html {
root /usr/local/nginx/;
index index.html index.htm;
}
# 访问模式:alias路径 会把 location路径 替换掉
# 这就是为什么有的页面root的可以正常访问,而alias的不可以
# 路径的末尾要加上 /,否则会有路径问题
# 相当于访问 /usr/local/nginx/
location /html {
alias /usr/local/nginx/;
index index.html index.htm;
}