Nginx 是一个高性能的 HTTP 与反向代理服务器,同时也可作为邮件代理服务器以及通用的 TCP/UDP 代理服务器,最初由 Igor Sysoev 编写。
其基于事件驱动(epoll)的异步非阻塞架构能够在极低资源消耗下支撑海量并发连接,是构建高并发 Web 服务与网关的核心组件。
1. 概述
1.1 常用的功能模块
Nginx 常用于以下场景,主要能力模块包括:
- 静态资源的部署
- Rewrite 地址重写(基于正则表达式)
- 反向代理
- 负载均衡:轮询、加权轮询、ip_hash、url_hash、fair
- Web 缓存
- 环境部署:高可用的运行环境
- 用户认证模块
1.2 核心组成
Nginx 运行时由以下核心部分组成:
- nginx 二进制可执行文件
- nginx.conf 配置文件
- error.log 错误的日志记录
- access.log 访问日志记录
2. 环境配置与安装
2.1 关闭 SELinux
下载地址:Index of /download/ (nginx.org)
使用 sestatus 查看状态,建议将其关闭:
vim /etc/selinux/config
修改 SELINUX=disabled。
2.2 安装依赖
源码编译需要以下依赖:
| 依赖 | 安装命令 |
|---|---|
| gcc | yum install -y gcc |
| pcre | yum install -y pcre pcre-devel |
| zlib | yum install -y zlib zlib-devel |
| openSSL | yum install -y openssl openssl-devel |
2.3 源码安装
wget https://nginx.org/download/nginx-1.26.1.tar.gz
//创建文件,便于管理
mkdir -p nginx/core
mv nginx-1.26.1.tar.gz nginx/core
解压缩并进入目录:
tar -xzf nginx-1.26.1.tar.gz
执行 configure:
./configure
编译(如没有 make 可执行 yum -y install make):
make
安装:
make install
未指定安装目录时,默认在
/usr/local/nginx/sbin,执行./nginx启动。在浏览器输入服务器 IP 访问 Nginx,出现默认欢迎页即测试成功:

2.4 YUM 安装
yum install -y yum-utils
sudo yum install -y nginx
2.5 源码复杂安装(自定义路径)
常用 configure 参数说明:
| 参数 | 说明 |
|---|---|
| –prefix=PATH | 安装目录 |
| –sbin-path=PATH | 指向执行程序文件路径 |
| –conf-path=PATH | 指向 nginx.conf 的路径 |
重新卸载 Nginx:rm -rf /usr/local/nginx、make clean
./configure --prefix=/usr/local/
nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/
local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf
--error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/
usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/
nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock
2.6 目录结构
可使用 tree 查看项目结构(yum install -y tree):
[root@localhost sbin]# tree /usr/local/nginx
/usr/local/nginx
├── client_body_temp
├── conf
│ ├── fastcgi.conf
│ ├── fastcgi.conf.default
│ ├── fastcgi_params
│ ├── fastcgi_params.default
│ ├── koi-utf
│ ├── koi-win
│ ├── mime.types
│ ├── mime.types.default
│ ├── nginx.conf
│ ├── nginx.conf.default
│ ├── scgi_params
│ ├── scgi_params.default
│ ├── uwsgi_params
│ ├── uwsgi_params.default
│ └── win-utf
├── fastcgi_temp
├── html
│ ├── 50x.html
│ └── index.html
├── logs
│ ├── access.log
│ ├── error.log
│ └── nginx.pid
├── proxy_temp
├── sbin
│ └── nginx
├── scgi_temp
└── uwsgi_temp
CGI(通用网关接口):从客户端发送请求和数据,服务端获取到请求和数据后可以调用 CGI 程序处理并响应结果给客户端的一种标准规范。
3. 服务的启停
Nginx 服务的控制方式分为两类:
- 信号控制:直接向 master 进程发送信号
- 命令行控制:通过
nginx -s signal发送指令
3.1 信号控制(多进程模型)
Nginx 默认采用多进程方式工作,可通过 ps -ef | grep nginx 查看进程:
root 31002 1 0 09:36 ?
00:00:00 nginx: master process ./nginx
nobody 31003 31002 0 09:36 ?
00:00:00 nginx: worker process
root 87869 2359 0 10:00 pts/0
00:00:00 grep --color=auto nginx
通过向 master 进程发送信号,可以控制 worker 进程等。
3.2 信号说明
| 信号 | 作用 |
|---|---|
| TERM/INT | 立即关闭服务 |
| QUIT | 等待并关闭服务 |
| HUP | 重读配置文件并使用 |
| USR1 | 重新打开日志文件,可用于日志切割 |
| USR2 | 平滑升级到最新的 Nginx |
| WINCH | 给所有 worker 进程发送 QUIT 指令 |
发送信号语法:kill -signal pid,例如:
kill -QUIT 13636
kill -QUIT `more ../logs/nginx.pid`
平滑升级流程:发送 USR2 信号给 master 进程,会重新开启对应的 master 与 worker 进程,系统中将出现两个 master 进程,新 master 的 PID 记录在 /usr/local/nginx/logs/nginx.pid,旧 master 的 PID 记录在 /usr/local/nginx/logs/nginx.pid.oldbin。随后再发送 QUIT 信号给旧 master 进程,待其处理完请求后再关闭:
kill -USR2 PID / kill -USR2 `cat /usr/local/nginx/logs/nginx.pid`
kill -QUIT PID / kill -QUIT `cat /usr/local/nginx/logs/nginx.pid.oldbin`
WINCH 信号:发送给 master 进程,让其控制 worker 进程不再接收新请求,处理完请求后关闭 worker 进程(master 进程不会被关闭):
kill -WINCH PID / kill -WINCH `cat /usr/local/nginx/logs/nginx.pid`
3.3 命令行参数
| 参数 | 说明 |
|---|---|
| -? , -h | 显示帮助 |
| -v | 显示版本并退出 |
| -V | 显示版本与 configure 选项并退出 |
| -t | 测试配置文件并退出(检测 nginx.conf 语法) |
| -T | 测试配置、打印测试文件并退出 |
| -q | 配置测试期间抑制非错误消息 |
| -s signal | 向 master 进程发送信号:stop、quit、reopen、reload |
| -p prefix | 设置 prefix 路径(默认 /usr/local/nginx/) |
| -e filename | 设置错误日志文件(默认 /usr/local/nginx/logs/error.log) |
| -c filename | 设置配置文件(默认 /usr/local/nginx/conf/nginx.conf) |
| -g directives | 在配置文件之外设置全局指令 |
其中 -s 信号的对应关系:
- stop:快速关闭(类似 TERM/INT)
- quit:等待关闭(类似 QUIT)
- reopen:重新打开日志(类似 USR1)
- reload:重载配置(类似 HUP)
-g 示例:
./nginx -g "pid logs/abc.pid;"
3.4 版本升级
3.4.1 使用 nginx 服务信号
cd /usr/local/nginx/sbin
mv nginx nginxold
cd ~/nginx/core/nginx-1.16.1/objs
cp nginx /usr/local/nginx/sbin
查看 nginx 进程 pid(ps -ef | grep nginx),平滑升级:
kill -USR2 `cat /usr/local/nginx/logs/nginx.pid`
//关闭旧进程
kill -QUIT `cat /usr/local/nginx/logs/nginx.oldbin`
3.4.2 使用 make 命令
cd /usr/local/nginx/sbin
mv nginx nginxold
cd ~/nginx/core/nginx-1.16.1/objs
cp nginx /usr/local/nginx/sbin
进入安装目录执行 make upgrade,查看是否更新完成:
./nginx -V
4. 配置目录结构
Nginx 配置整体分为:全局块、events 块、http 块。http 块中可以配置多个 server 块,每个 server 块又可配置多个 location 块。
4.1 配置文件整体结构
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
4.2 全局块指令
4.2.1 user 指令
用于配置运行 Nginx 服务器 worker 进程的用户和用户组。
| 语法 | user user [group] |
|---|---|
| 默认值 | nobody |
| 位置 | 全局块 |
该属性也可在编译时指定:./configure --user=user --group=group
使用步骤:
- 设置用户信息
www,在 nginx.conf 中配置,会报“没有该用户”的错误,此时需要useradd www;
[root@localhost sbin]# ./nginx -t
nginx: [emerg] getpwnam("www")
failed in /usr/local/nginx/conf/nginx.conf:2
nginx: configuration file /usr/
local/nginx/conf/nginx.conf test failed
- 若将 html 目录改为
/root/html会返回 403(权限不足),改为/home/www/html即可正常访问index.html。
user 指令可以指定启动运行工作进程的用户和用户组,使系统的权限访问控制更加精细,也更加安全。
4.2.2 worker_processes 与 master_process 指令
master_process 指定是否开启工作进程:
| 语法 | master_process on | off |
|---|---|
| 默认值 | master_process on |
| 位置 | 全局块 |
worker_processes 配置工作进程数量,建议与服务器 CPU 内核数保持一致:
| 语法 | worker_processes num/auto |
|---|---|
| 默认值 | 1 |
| 位置 | 全局块 |
设置为 2 时效果示意:

4.2.3 其他全局指令
- daemon:设定 Nginx 是否以守护进程方式启动。守护进程是 Linux 后台执行的服务进程,独立于控制终端,不会随终端关闭而停止。
| 语法 | daemon on/off |
|---|---|
| 默认值 | daemon on |
| 位置 | 全局块 |
- pid:配置 Nginx 当前 master 进程号 ID 存储的文件路径。
| 语法 | pid file |
|---|---|
| 默认值 | /usr/local/nginx/logs/nginx.pid |
| 位置 | 全局块 |
- error_log:配置错误日志存放路径。
| 语法 | error_log file [日志级别] |
|---|---|
| 默认值 | /usr/local/nginx/logs/nginx.pid |
| 位置 | 全局块、http、server、location |
日志级别:debug info notice warn error crit alert emerg,建议不要使用 info 以下级别。
- include:引入其他配置文件,使 Nginx 配置更加灵活。
| 语法 | include file |
|---|---|
| 默认值 | 无 |
| 位置 | any |
例如 include main.conf,可将部分配置写入 main.conf 中。
4.3 events 块指令
4.3.1 accept_mutex
用来设置 Nginx 网络连接序列化,解决“惊群问题”。
| 语法 | accept_mutex on|off |
|---|---|
| 默认值 | accept_mutex on |
| 位置 | events |
4.3.2 multi_accept
用来设置是否允许同时接受多个网络连接。
| 语法 | multi_accept on|off |
|---|---|
| 默认值 | multi_accept off |
| 位置 | events |
建议开启 multi_accept on。
4.3.3 worker_connections
用来配置单个 worker 进程最大的连接数。
| 语法 | worker_connections number |
|---|---|
| 默认值 | worker_connections 512 |
| 位置 | events |
4.3.4 use
用来设置 Nginx 服务器选择哪种事件驱动来处理网络消息。
| 语法 | use method |
|---|---|
| 默认值 | 根据操作系统定 |
| 位置 | events |
method 可选:select/poll/epoll/kqueue,建议设置 epoll。
4.3.5 指令配置实例
events{
accept_muyex on;
multi_accpet on;
worker_commections 1024;
use epoll;
}
启动测试:
启动测试
./nginx -t
./nginx -s reload
4.4 http 块指令
4.4.1 default_type
用来配置 Nginx 响应前端请求默认的 MIME 类型。
| 语法 | default_type mime-type |
|---|---|
| 默认值 | default_type text/plain |
| 位置 | http、server、location |
4.4.2 access_log 与 error_log
- access.log:记录用户访问的请求。
- error.log:记录 Nginx 本身运行时的错误信息(不记录用户访问请求)。
access_log 设置用户访问日志的相关属性:
| 语法 | access_log path[format[buffer=size]] |
|---|---|
| 默认值 | access_log logs/access.log combined |
| 位置 | http、server、location |
4.4.3 log_format
用来指定日志的输出格式。
| 语法 | log_format name [escape=default|json|none] string |
|---|---|
| 默认值 | log_format combined “…” |
| 位置 | http |
log_format myformat "========>";
access_log logs/mylog.log myformat;
4.4.4 sendfile
设置是否用 sendfile 传输文件,可大幅提升 Nginx 处理静态资源的性能。
| 语法 | sendfile on | off |
|---|---|
| 默认值 | sendfile off |
| 位置 | http |
4.4.5 keepalive_timeout 与 keepalive_requests
keepalive_timeout 设置长连接的超时时间:
| 语法 | keepalive_timeout time |
|---|---|
| 默认值 | keepalive_timeout 75s |
| 位置 | http、server、location |
keepalive_requests 设置 keep-alive 的次数:
| 语法 | keepalive_requests number |
|---|---|
| 默认值 | keepalive_requests 100 |
| 位置 | http、server、location |
有些接口需要返回指定的文本字符串或 JSON,若逻辑非常简单或固定字符串,可直接用 Nginx 实现,减少服务器资源占用、提升性能。
4.5 server 与 location 块
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
4.6 基础配置实例
user www;
worker_processes 2;
err_log logs/error.log;
pid logs/nginx.pid;
events {
accept_mutex on;
multi_accept on;
use epool;
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format serve1 '======>server1';
log_format serve2 '======>server2'
include /home/www/conf.d/*.conf;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
4.7 配置为系统服务
(1) 创建 service 文件:
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
ExexReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
wantedBy=defauly.target
(2) 授权:chmod 755 /usr/lib/systemd/system/nginx.service
(3) 使用系统命令操作:
| 操作 | 命令 |
|---|---|
| 启动 | systemctl start nginx |
| 停止 | systemctl stop nginx |
| 重启 | systemctl restart nginx |
| 重新加载配置 | systemctl reload nginx |
| 查看状态 | systemctl status nginx |
| 开机启动 | systemctl enable nginx |
4.8 命令加入系统环境
1.vim /etc/profile
export PATH=$PATH:/usr/local/nginx/sbin
2.source /etc/peofile
5. 静态资源部署
5.1 listen
| 语法 | listen address[:port] [default_server]… |
|---|---|
| 默认值 | listen *:80 | *:8000 |
| 位置 | server |
default_server 为标识符号,用来设置默认主机:
server{
listen 8080 default_server
}
5.2 server_name
用来设置虚拟主机服务名称,可用 127.0.0.1、localhost、域名。
| 语法 | server_name name…; |
|---|---|
| 默认值 | server_name “”; |
| 位置 | server |
匹配方式分为:精确匹配、通配符匹配、正则表达式匹配。
5.2.1 精确匹配
server{
server_name www.nginx.org;
}
hosts 是一个没有扩展名的系统文件:Windows 位于
C:\Windows\System32\drivers\etc,CentOS 位于/etc/hosts。
5.2.2 通配符匹配
通配符可以出现在开头或结尾,但不能用在域名的中部:
server{
server_name *.richu.cn
}
5.2.3 正则表达式匹配
由于 Nginx 配置中经常出现正则表达式,下面介绍常见用法:
- 开始与结束:
^匹配输入字符串的开始;$匹配输入字符串的结束。 - 匹配次数:
?匹配 0 次或 1 次;+匹配 1 次或多次;*匹配 0 次或多次;{n}匹配 n 次;{n,}至少匹配 n 次;{n,m}匹配 n 至 m 次。 - 匹配字符:
\用于转义.匹配除\n之外的任意字符[xyz]匹配 xyz 中任意一个字符[a-z]匹配任意小写字母;[^a-z]取反,匹配除小写字母之外的任意字符[A-Z]匹配任意大写字母;[a-zA-Z]匹配任意字母[0-9]匹配任意数字,等价于\d;[^0-9]匹配任意非数字,等价于\D\s匹配任何空白字符;\S匹配任何非空白字符\w匹配字母、数字、下划线(A-Z a-z 0-9 _)x|y匹配 x 或 y
在前面加上 ~ 表示为正则表达式:
server_name example.com ~^www\d+\.example\.com$
server_name ~^www\\.(\w+)\\.com
location / {
return 200 $1 $2
}
$1 可以匹配到 (\w+) 中匹配的内容。
5.2.4 匹配执行顺序
精确匹配 → 通配符在开始 → 通配符在结尾 → 正则表达式 → 默认 default_server。
5.3 location
用来设置请求的 URL。
| 语法 | location [ = | ~ |
|---|---|
| 默认值 | —- |
| 位置 | server, location |
=用于不包含正则表达式的 uri 前,必须与指定内容精确匹配:
location =/abc {
}
~正则匹配,区分大小写;~*正则匹配,不区分大小写。^~用于不包含正则表达式的 uri 前,功能与不加符号一致,唯一不同是:若模式匹配则停止搜索其他模式。
5.4 root 与 alias
root:设置请求的根目录。
| 语法 | root path |
|---|---|
| 默认值 | root html |
| 位置 | http、server、location |
alias:用来更改 location 的 url。
| 语法 | alias path |
|---|---|
| 默认值 | —- |
| 位置 | location |
- root:root 路径 + location 后面的地址
- alias:不会加上 location 后面的地址(alias 是目录别名的定义)
5.5 index
设置网站的默认首页。
| 语法 | index file … |
|---|---|
| 默认值 | index index.html; |
| 位置 | http、server、location |
后面可配置多个选项,匹配到其中一个后不再匹配后续设置。
5.6 error_page
设置网站的错误页面。
| 语法 | error_page code … [=[response]] uri; |
|---|---|
| 默认值 | —- |
| 位置 | http、server、location |
(1) 跳转指定页面:
error_page 404 www.richu.cn
(2) 重定向地址:
error_page 404 /50x.html
(3) 使用 location 的 @ 符号完成错误信息匹配:
server{
error_page 404 @jump_to_error;
location @jump_to_error {
default_type text/plain;
return 404 'Not Found Html'
}
}
(4) 可选项 =[response] 将响应代码更改为另一个:
error_page 404 =200 /50x.html
6. 静态资源优化配置
6.1 sendfile
用来开启高效的文件传输模式。
| 语法 | sendfile on|off |
|---|---|
| 默认值 | sendfile off; |
| 位置 | http、server、location |
6.2 tcp_nopush
需要打开 sendfile,用来提升网络包传输效率。
| 语法 | tcp_nopush on|off |
|---|---|
| 默认值 | tcp_nopush off; |
| 位置 | http、server、location |
6.3 tcp_nodelay
需要打开 keep-alive,用来提升网络包传输的实时性。
| 语法 | tcp_nodelay on|off |
|---|---|
| 默认值 | tcp_nodelay on; |
| 位置 | http、server、location |
推荐组合:
sendfile on
tcp_nopush on
tcp_nodelay on
6.4 gzip
开启或关闭 gzip 功能。
| 语法 | gzip on|off |
|---|---|
| 默认值 | gzip off; |
| 位置 | http、server、location |
6.5 gzip_types
根据响应页面的 MIME 类型选择性开启 Gzip 压缩功能。
| 语法 | gzip_types mime-type |
|---|---|
| 默认值 | gzip_types text/html; |
| 位置 | http、server、location |
gzip_types *;
6.6 gzip_comp_level
设置压缩程度,1-9:1 程度低、效率高;9 程度高、效率低。
| 语法 | gzip_comp_level level |
|---|---|
| 默认值 | gzip_comp_level 1; |
| 位置 | http、server、location |
6.7 gzip_vary
告诉接收方,所发送的数据经过了 gzip 压缩处理(Vary: Accept-Encoding)。
| 语法 | gzip_vary on|off |
|---|---|
| 默认值 | gzip_vary off; |
| 位置 | http、server、location |
6.8 gzip_buffers
处理请求压缩的缓冲区数量和大小。
| 语法 | gzip_buffers number size |
|---|---|
| 默认值 | gzip_buffers 32 4k | 16 8k; |
| 位置 | http、server、location |
number 为向系统申请缓存空间数量,size 为每个缓冲空间大小,建议不设置、使用默认值即可。
6.9 gzip_disable
针对不同客户端请求,选择性开启和关闭 Gzip。regex 根据 user-agent 设置,支持正则表达式:
| 语法 | gzip_disable regex …; |
|---|---|
| 默认值 | — |
| 位置 | http、server、location |
gzip_disable "MSIE [1-6]\\."; 禁用IE1-6版本的gzip
6.10 gzip_http_version
针对不同 HTTP 协议版本,选择性开启和关闭 Gzip,建议使用默认值。
| 语法 | gzip_http_version version 1.0|1.1 |
|---|---|
| 默认值 | gzip_http_version 1.1 |
| 位置 | http、server、location |
6.11 gzip_min_length
针对传输数据大小,选择性开启和关闭 Gzip(单位:字节 bytes、千字节 kb、兆 m)。
| 语法 | gzip_min_length length |
|---|---|
| 默认值 | gzip_min_length 20 |
| 位置 | http、server、location |
6.12 gzip_proxied
设置是否对服务端返回的结果进行 gzip 压缩。
| 语法 | gzip_proxied off|expired|no-cache|no_store|private|no_last_modified|no_etag|auth|any |
|---|---|
| 默认值 | gzip_proxied off; |
| 位置 | http、server、location |
完整配置示例:
gzip on;
gzip_types *;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_buffers 4 1024;
gzip_http_version 1.1;
gzip_vary on;
gzip_disable "MISE [1-6]\.";
gzip_proxied off;
配置后使用 vim nginx_gzip.conf。
6.13 sendfile 与 Gzip 共存(gzip_static)
gzip_static 检查与文件同名的 .gz 文件,在 response 中以 gzip 相关 header 返回 .gz 文件内容。
| 语法 | gzip_static on | off | always |
|---|---|
| 默认值 | gzip_static off; |
| 位置 | http、server、location |
报错:
nginx: [emerg] unknown directive "gzip_static" in /usr/local/nginx/conf/nginx.conf:33
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
需要为 Nginx 添加 http_gzip_static 模块:
(1) 查看配置参数:nginx -V
--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/
nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/
local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/
logs/error.log --http-log-path=/usr/local/nginx/logs/access.log
--pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/
nginx/logs/nginx.lock
(2) 将 nginx 二进制目录改名:mv nginx nginxold
(3) make clean
(4) 使用 ./configure 配置参数:
./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/
sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/
usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/
logs/error.log --http-log-path=/usr/local/nginx/logs/access.log
--pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/
nginx/logs/nginx.lock --with-http_gzip_static_module
(5) make
(6) cd objs 并 cp nginx /usr/local/nginx/sbin
(7) make upgrade
使用测试:
gzip promise.js
#响应标头
accept-ranges:bytes
connection:keep-alive
content-encoding:gzip
content-length:1065
content-type:application/javascript
etag:"66b71e2a-429"
last-modified:Sat, 10 Aug 2024 08:00:42 GMT
server:nginx/1.26.1
vary:Accept-Encoding
7. 静态资源的缓存处理
缓存用于减少等待数据的时间,分为:
- 客户端缓存:浏览器缓存
- 服务端缓存:Nginx / Redis / Memcached 等
7.1 浏览器缓存执行流程
| header | 说明 |
|---|---|
| Expires | 缓存过期的日期和时间 |
| Cache-Control | 设置和缓存相关的配置信息 |
| Last-Modified | 设置请求资源的最后修改时间 |
| ETag | 请求变量的实体标签的当前值,比如文件的 MD5 值 |
7.2 expires 指令
控制页面缓存。
| 语法 | expires [modified] time expires epoch |max | off |
|---|---|
| 默认值 | expires off; |
| 位置 | http、server、location |
- time:正数或负数,指定过期时间;负数则 Cache-Control 为
no-cache,正数则 Cache-control 的值为max-age=time。 - epoch:指定为 1970 年,Cache-control 的值为
no-cache。 - max:指定 2037 年,Cache-control 的值为 10 年。
- off:默认不缓存。
location ~ .*\.(html|js|css|png)${
expires 1000; //1000秒
}
7.3 add_header 指令
添加指定的响应头和响应值。
| 语法 | add_header name value [always] |
|---|---|
| 默认值 | —- |
| 位置 | http、server、location |
Cache-control: must-revalidate 可缓存但必须再向源服务器进行确认
Cache-control: no-cache 缓存前必须确认其有效性
Cache-control: no-store 不缓存请求或响应的任何内容
Cache-control: no-transform 代理不可更改媒体类型
Cache-control: public 可向任意方提供响应的缓存
Cache-control: private 仅向特定用户返回响应
#要求中间缓存服务器对缓存的响应有效性再次确认
Cache-control: proxy-revalidate
Cache-Control: max-age=<seconds>
响应最大Age值
Cache-control:
s-maxage=<seconds>
公共缓存服务器响应的最大Age值
8. 跨域问题与防盗链
8.1 跨域问题
浏览器的同源策略是最基本最核心的安全功能(协议、域名、端口相同),缺少它会影响浏览器正常功能。
通过 add_header 设置跨域响应头:
| 响应头 | 说明 |
|---|---|
| Access-Control-Allow-Origin | 允许跨域访问的源地址信息,如 * |
| Access-Control-Allow-Methods | 允许跨域请求的请求方式,如 GET、POST |
location /get{
add_header Access-Control-Allow-Origin http:192.168.200.133;
add_header Access-Control-Allow-Methods GET,POST,DELETE,PUT
}
8.2 静态资源防盗链
HTTP 头信息 Referer:浏览器向 Web 服务器发送请求时,一般都会带上 Referer,告诉服务器请求是从哪个页面链接过来的。
valid_referers:Nginx 会查看 referer 并自动与后面的内容匹配,匹配到则将 $invalid_referer 变量置为 0,未匹配到则置为 1。
| 语法 | valid_referers none | blocked | server_names | string |
|---|---|
| 默认值 | —- |
| 位置 | server、location |
- none:Header 中 Referer 为空时允许访问
- blocked:Header 中 Referer 不为空
- server_names:指定域名和 IP
- string:支持正则表达式和带
*的字符串
9. URL 重写(Rewrite)
Rewrite 依赖 PCRE 支持,对应模块 ngx_http_rewrite_module。
9.1 set 与内置变量
| 语法 | set $variable value |
|---|---|
| 默认值 | —- |
| 位置 | server、location、if |
server {
listen 8080;
server_name localhost;
location /server{
//定义
set $name "test";
set $age 18;
default_type text/plain;
//使用
return 200 $name=$age;
}
}
常用内置变量说明:
$args
变量中存放了请求URL中的请求参数。
比如http://192.168.200.133/server?arg1=value1&args2=value2中
的"arg1=value1&arg2=value2",功能和$query_string一样。
$http_user_agent
变量存储的是用户访问服务的代理信息
(如果通过浏览器访问,记录的是浏览器的相关版本信息)
$host
变量存储的是访问服务器的server_name值
$document_uri
变量存储的是当前访问地址的URI。
比如http://192.168.200.133/server?i
d=10&name=zhangsan中的"/server",功能和$uri一样
$document_root
变量存储的是当前请求对应location的root值,
如果未设置,默认指向Nginx自带html目录所在位置
$content_length
变量存储的是请求头中的Content-Length的值
$content_type
变量存储的是请求头中的Content-Type的值
$http_cookie
变量存储的是客户端的cookie信息,
可以通过add_header Set-Cookie'cookieName=cookieValue'来添加cookie数据
$limit_rate
变量中存储的是Nginx服务器对网络连接速率的限制,
也就是Nginx配置中对limit_rate指令设置的值,默认是0,不限制。
$remote_addr
变量中存储的是客户端的IP地址
$remote_port
变量中存储了客户端与服务端建立连接的端口号
$remote_user
变量中存储了客户端的用户名,需要有认证模块才能获取
$scheme
变量中存储了访问协议
$server_addr
变量中存储了服务端的地址
$server_name
变量中存储了客户端请求到达的服务器的名称
$server_port
变量中存储了客户端请求到达服务器的端口号
$server_protocol
变量中存储了客户端请求协议的版本,比如"HTTP/1.1"
$request_body_file
变量中存储了发给后端服务器的本地文件资源的名称
$request_method
变量中存储了客户端的请求方式,比如"GET","POST"等
$request_filename
变量中存储了当前请求的资源文件的路径名
$request_uri
变量中存储了当前请求的URI,并且携带请求参数,
比如http://192.168.200.133/server?id=10&name=zhangsan中的"/server?
日志格式示例:
log_format main
'$remote_addr-$request - $status
- $request_uri - $http_user_agent';
server {
listen 8080;
server_name localhost;
location /server{
set $name "test";
set $age 18;
default_type text/plain;
return 200 $name=$age;
}
192.168.3.1 - - [11/Aug/2024:02:53:25 -0400] "GET /server
HTTP/1.1" 200 7 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/127.0.0.0 Safari/537.36"
9.2 if 指令
条件判断。
| 语法 | if (condition) |
|---|---|
| 默认值 | —- |
| 位置 | server、location |
空字符串和 0 为 false,其他都为 true。使用 = 和 != 比较字符串(字符串不需要加引号);~ 正则匹配、~* 不区分大小写。
if ($http_user_agent ~ MSIE){
#$http_user_agent是否包含MISE,如果包含返回true
}
-f指定文件是否存在
if (!-f $request_file){
}
目录 -d、请求目录或文件 -e、是否可执行 -x。
9.3 break 指令
| 语法 | break |
|---|---|
| 默认值 | —- |
| 位置 | server、location |
终止此次操作并重定向操作。
9.4 return 指令
用于完成对请求的处理,直接向客户端返回;return 之后的所有 Nginx 配置均无效。
| 语法 | return code [text] return code URL return html |
|---|---|
| 默认值 | —- |
| 位置 | server、location、if |
9.5 rewrite 指令
| 语法 | rewrite regex replacement [flag] |
|---|---|
| 默认值 | —- |
| 位置 | server、location、if |
regex 用来匹配 URI 的正则表达式;匹配成功后用于替换 URI 的内容,若以 http 或 https 开头则不再继续向下匹配。
location /rewrite{
rewrite ^/rewrite/(test)\w*$ /$1;
}
//访问http://ip/rewrite/testabc -------> /test
flag 用来设置 rewrite 对 uri 的处理行为:
- last:作为一个新的 uri,可使用其他 location 块进行处理
location /rewrite{
rewrite ^/rewrite/(test)\w*$ /$1 last;
}
- break:作为一个新的 uri,在本 location 中继续处理,不转向其他 location
location /rewrite{
rewrite ^/rewrite/(test)\w*$ /$1 break;
}
- redirect:指明为重定向,状态码 302
location /rewrite{
rewrite ^/rewrite/(test)\w*$ /$1 redirect;
}
- permanent:状态码 301,永久重定向
location /rewrite{
rewrite ^/rewrite/(test)\w*$ /$1 permanent;
}
9.6 rewrite_log
配置是否开启 URL 重写日志的输出功能。
| 语法 | rewrite_log on|off |
|---|---|
| 默认值 | —- |
| 位置 | http、server、location、if |
rewrite_log on;
err_log logs_error.log notice;
9.7 域名镜像
将相同的网站分别放置在不同的服务器上,并分别使用单独的 URL 访问,其中一台为主站,其余为镜像网站。
server_name_in_redirect on | off:
- on:重定向为
http://server_name:8082/目录名/ - off:重定向为
http://原URL的ip地址:8082/目录名/
9.8 目录合并
搜索引擎优化(SEO)利用搜索引擎规则提高网站在搜索结果中的排名。例如目录层级有 5 层:
http://www.web.name/server/11/22/33/44/20.html
location {
rewrite ^/server-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)/
([0-9])\.html$ /server/$1/$2/$3/$4/$5.html
}
10. Nginx 代理
10.1 正向代理
location{
listen 82;
location / {
resolver #设置DNS的IP 用来解析proxy_pass中的域名
proxy_pass http://$host$request_uri;
}
}
在客户端配置代理服务器:

10.2 反向代理
10.2.1 proxy_pass
| 语法 | proxy_pass URL |
|---|---|
| 默认值 | —- |
| 位置 | location |
URL 为设置的被代理的服务器地址:
proxy_pass http://192.168.200.146/
proxy_pass http://192.168.200.146
# 当后面没有加上/则会吧location的请求路径拼上去,加上则不会
10.2.2 proxy_set_header
更改请求头信息,然后将新的请求头信息发送到代理服务器。
| 语法 | proxy_set_header field value; |
|---|---|
| 默认值 | proxy_set_header Host $proxy_host proxy_set_header Connection close; |
| 位置 | http、server、location |
location / {
proxy_pass http://192.168.200.146:8080/;
proxy_set_header username TOM; #使用 $http_username
}
10.2.3 proxy_redirect
重置 Location 和 Refresh 的值。
| 语法 | proxy_redirect redirect replacement; proxy_redirect default; proxy_redirect off; |
|---|---|
| 默认值 | proxy_redirect default |
| 位置 | http、server、location |
proxy_redirect http://192.168.200.146/ http://192.168.200.133/:redirect 为目标 Location 的值,replacement 为需要替换的值。proxy_redirect default:将 location 的 uri 变量作为 replacement,将 proxy_pass 变量作为 redirect 进行替换。proxy_redirect off:关闭 proxy_redirect 功能。
10.3 安全控制(SSL)
通过代理分开客户端到服务端的连接,在反向代理之前设置防火墙,仅留一个入口供代理服务器访问,即安全隔离。
10.3.1 对流量进行加密
将 HTTP 转换为 HTTPS 协议。SSL(安全套接层)/ TLS(传输层安全):HTTP 是明文传输数据、有安全问题,HTTPS 是加密传输(相当于 HTTP+SSL),可防止流量被劫持。
10.3.2 添加 SSL 支持
复制 nginx 二进制文件并重新编译,加入 --with-http_ssl_module:
参数
--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/
nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/
local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/
logs/error.log --http-log-path=/usr/local/nginx/logs/access.log
--pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/
nginx/logs/nginx.lock --with-http_gzip_static_module
./configure --with-http_ssl_modules
make
# 将 objs 下的 nginx 复制覆盖
make upgrade
10.3.3 ssl
| 语法 | ssl on|off |
|---|---|
| 默认值 | ssl off |
| 位置 | http、server |
server{
listen 443 ssl
}
10.3.4 ssl_certificate
指定 PEM 格式的证书。
| 语法 | ssl_certificate file |
|---|---|
| 默认值 | —— |
| 位置 | http、server |
10.3.5 ssl_session_cache
配置 SSL 会话的缓存。
| 语法 | ssl_session_cache off|none|[builtin[:size]]|[shared:name:size] |
|---|---|
| 默认值 | ssl_session_cache none; |
| 位置 | http、server |
- off:禁用缓存
- none:禁用会话缓存
- builtin:内置 OpenSSL 缓存,仅在一个工作进程中使用
- shared:所有工作进程之间共享缓存,用 name 和 size 指定
10.3.6 ssl_session_timeout
开启会话后,设置客户端能反复使用缓存中会话参数的时间。
| 语法 | ssl_session_timeout time |
|---|---|
| 默认值 | ssl_session_timeout 5m //5分钟 |
| 位置 | http、server |
10.3.7 ssl_ciphers
指出允许的密码,为 OpenSSL 支持的格式(可用 openssl ciphers 查看)。
TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SH
A256:TLS_AES_128_CCM_SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AE
S256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1
305:ECDHE-ECDSA-AES256-CCM:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES
128-GCM-SHA256:ECDHE-ECDSA-AES128-CCM:ECDHE-ECDSA-AES128-SHA256:ECDHE-
RSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:ECDHE-EC
DSA-AES128-SHA:ECDHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES256-CCM:AES12
8-GCM-SHA256:AES128-CCM:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-
SHA:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES256
-CCM:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-CCM:DHE-RSA-AES256-SHA25
6:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:PSK-AES2
56-GCM-SHA384:PSK-CHACHA20-POLY1305:PSK-AES256-CCM:PSK-AES128-GCM-SHA2
56:PSK-AES128-CCM:PSK-AES256-CBC-SHA:PSK-AES128-CBC-SHA256:PSK-AES128-
CBC-SHA:DHE-PSK-AES256-GCM-SHA384:DHE-PSK-CHACHA20-POLY1305:DHE-PSK-AE
S256-CCM:DHE-PSK-AES128-GCM-SHA256:DHE-PSK-AES128-CCM:DHE-PSK-AES256-C
BC-SHA:DHE-PSK-AES128-CBC-SHA256:DHE-PSK-AES128-CBC-SHA:ECDHE-PSK-CHAC
HA20-POLY1305:ECDHE-PSK-AES256-CBC-SHA:ECDHE-PSK-AES128-CBC-SHA256:ECD
HE-PSK-AES128-CBC-SHA
| 语法 | ssl_ciphers ciphers |
|---|---|
| 默认值 | ssl_ciphers HIGH:!aNULL:!MD5 |
| 位置 | http、server |
10.3.8 ssl_prefer_server_ciphers
| 语法 | ssl_prefer_server_ciphers on|off |
|---|---|
| 默认值 | ssl_prefer_server_ciphers off |
| 位置 | http、server |
10.4 生成证书
购买域名与 SSL 证书,或使用 openssl 自签:
mkdir /root/cert
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key
-out server.crt
10.5 SSL 配置示例
server {
listen 443 ssl;
server_name localhost;
ssl_certificate cert.pem;
ssl_certificate_key cert.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root html;
index index.html index.htm;
}
}
若证书密钥长度过小会报错:
#报错
SSL_CTX_use_certificate("/root/
cert/server.crt") failed (SSL:
error:140AB18F:SSL
routines:SSL_CTX_use_certificate:e
e key too small)
nginx: configuration file /usr/
local/nginx/conf/nginx.conf test failed
将密钥大小改为 2048:
mkdir /root/cert
openssl genrsa -des3 -out server.key 2048
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key
-out server.crt

10.6 反向代理的优化
10.6.1 proxy_buffering
开启或关闭代理服务器的缓冲区。
| 语法 | proxy_buffering on | off |
|---|---|
| 默认值 | proxy_buffering on |
| 位置 | http、server、location |
10.6.2 proxy_buffers
单个连接读取响应的缓存区个数和大小(number 个数,size 大小)。
| 语法 | proxy_buffers number size |
|---|---|
| 默认值 | proxy_buffers 8 4k |
| 位置 | http、server、location |
10.6.3 proxy_buffer_size
被代理服务器获取的第一部分响应数据的大小。
| 语法 | proxy_buffer_size size |
|---|---|
| 默认值 | proxy_buffer_size 8k |
| 位置 | http、server、location |
10.6.4 proxy_temp_path
当缓存区满之后,会被临时存放在磁盘中,设置文件路径。
| 语法 | proxy_temp_path path |
|---|---|
| 默认值 | proxy_temp_path proxy_temp |
| 位置 | http、server、location |
10.6.5 proxy_temp_file_write_size
设置磁盘缓存文件的大小。
| 语法 | proxy_temp_file_write_size size |
|---|---|
| 默认值 | proxy_temp_file_write_size 8k |
| 位置 | http、server、location |
11. 负载均衡
将请求分配给不同的服务器。扩展方式:
- 横向扩展:提升服务器数量
- 纵向扩展:提升单机硬件
11.1 处理方式
用户手动选择,提供不同线路、不同服务器的链接。
11.2 四层与七层负载均衡
基于 OSI(开放式系统互联模型):
- 四层负载均衡:传输层,基于 IP+PORT 的负载均衡,不识别域名。
- 七层负载均衡:应用层,基于虚拟 URL 或主机 IP 的负载均衡,识别域名。
实际使用模式常为:四层(LVS)+ 七层(Nginx)。
11.3 Nginx 七层负载均衡
11.3.1 upstream
定义一组服务器,监听不同端口的服务器。
| 语法 | upstream name {} |
|---|---|
| 默认值 | —— |
| 位置 | http |
11.3.2 server
指定后端服务器的名称与参数,可使用域名、IP、端口或 unix-socket。
| 语法 | server name [parameters] |
|---|---|
| 默认值 | —— |
| 位置 | upstream |
upstream 服务名{
server http://192.168.3.133:8080;
server http://192.168.3.133:8081;
}
http://服务名 //访问
后端服务器状态:
| 状态 | 概述 |
|---|---|
| down | 当前 server 暂时不参与负载均衡 |
| backup | 标记为备份服务器,当主服务器不可用时用来传递请求 |
| max_conns | 设置代理服务器同时活动链接的最大数量,默认为 0 |
| max_fails | 允许请求代理服务器失败的次数,默认 1 |
| fail_timeout | max_fails 后,服务暂停的时间,默认 10s |
11.3.3 down 状态
upstream 服务名{
server http://192.168.3.133:8080 down;
server http://192.168.3.133:8081;
}
11.4 负载均衡策略
| 名称 | 说明 |
|---|---|
| 轮询 | 默认 |
| weight | 权重,默认 1,权重越高被分配的请求越多 |
| ip_hash | 依据 ip 分配,每个访客固定访问一个后端服务 |
| least_conn | 依据最少连接方式,优先分配给连接数少的后端服务器 |
| url_hash | 依据 url 分配,相同 url 被分配到同一个后端服务 |
| fair | 依据响应时间,响应时间短的服务优先分配 |
11.4.1 轮询
轮询不需要做任何配置,按请求时间逐个分配到不同后端服务器。
11.4.2 加权轮询
weight=number 默认为 1,权重越大被分配请求的概率越大:
upstream webservers{
server 192.168.100.128:8080 weight=90 ;
server 192.168.100.129:8080 weight=10 ;
}
11.4.3 ip_hash
| 语法 | ip_hash; |
|---|---|
| 默认值 | —— |
| 位置 | upstream |
upstream webservers{
ip_hash;
server 192.168.100.128:8080;
server 192.168.100.129:8080;
}
11.4.4 least_conn
upstream webservers{
least_conn;
server 192.168.100.128:8080;
server 192.168.100.129:8080;
}
11.4.5 url_hash
同一个 url 会到达同一个服务器:
upstream webservers{
hash $request_uri
server 192.168.100.128:8080;
server 192.168.100.129:8080;
}
11.4.6 fair
下载 nginx-upstream-fair 模块:gnosek/nginx-upstream-fair,解压放入 /root/nginx/module/fair。
./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/
sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/
usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/
logs/error.log --http-log-path=/usr/local/nginx/logs/access.log
--pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/
nginx/logs/nginx.lock --with-http_gzip_static_module
--with-http_ssl_module --add-module=/root/nginx/module/fair
编译可能报错:
/root/nginx/module/fair/ngx_http_upstream_fair_module.c:
在函数‘ngx_http_upstream_init_fair_rr’中:
/root/nginx/module/fair/ngx_http_upstream_fair_module.c:543:28:
错误:‘ngx_http_upstream_srv_conf_t’ {
或称 ‘struct ngx_http_upstream_srv_conf_s’}
没有名为‘default_port’的成员
if (us->port == 0 && us->default_port == 0) {
^~
/root/nginx/module/fair/ngx_http_upstream_fair_module.c:553:51:
错误:‘ngx_http_upstream_srv_conf_t’ {
或称 ‘struct ngx_http_upstream_srv_conf_s’}
没有名为‘default_port’的成员
u.port = (in_port_t) (us->port ? us->port : us->default_port);
^~
make[1]: ***
[objs/Makefile:1254:objs/addon/fair/ngx_http_upstream_fair_module.o] 错误 1
make[1]: 离开目录“/root/nginx/core/nginx-1.26.1”
make: *** [Makefile:10:build] 错误 2
报错解决方案:进入 nginx 目录 /src/http,编辑 vim ngx_http_upstream.h,为结构体补充 default_port 成员:
struct ngx_http_upstream_srv_conf_s {
ngx_http_upstream_peer_t peer;
void **srv_conf;
ngx_array_t
*servers; /* ngx_http_upstream_server_t */
ngx_uint_t flags;
ngx_str_t host;
u_char *file_name;
ngx_uint_t line;
in_port_t port;
in_port_t default_port;
ngx_uint_t no_port; /* unsigned no_port:1 */
#if (NGX_HTTP_UPSTREAM_ZONE)
ngx_shm_zone_t *shm_zone;
#endif
};
重新 make 后配置使用:
upstream webservers{
fair;
server 192.168.100.128:8080;
server 192.168.100.129:8080;
}
11.5 四层负载均衡(stream)
添加 --with-stream 模块:
--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/
nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/
local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/
logs/error.log --http-log-path=/usr/local/nginx/logs/access.log
--pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/
nginx/logs/nginx.lock --with-http_gzip_static_module
--with-http_ssl_module --add-module=/root/nginx/module/
fair --with-stream
11.5.1 stream 指令
和 http 同级,指定服务器指令的配置文件上下文。
| 语法 | stream; |
|---|---|
| 默认值 | —— |
| 位置 | main |
11.6 Redis / Tomcat 代理示例
Redis 下载:https://redis.io/downloads/#redis-downloads
tar -zxf redis.tar.gz
make PREFIX=/usr/local/redis/redis01 install
cd /usr/local/redis/redis01
vim redis.conf
# - port 6379
# - daemonize yes
启动:./redis-server ../redis.conf,bind 0.0.0.0 允许其他主机访问,客户端 redis-cli -h 192.168.3.133 -p 6379。
通过 stream 代理 Redis:
stream{
upstream redisbackend{
server 192.168.3.133:6379;
server 192.168.3.133:6378;
}
server{
listen 81;
proxy_pass redisbackend;
}
}
Tomcat:
tar -zxf tomcat.tar.gz
cd tomcat/bin
./startup
12. Nginx 缓存集成
12.1 proxy_cache_path
用于指定缓存文件的存放路径。
| 语法 | proxy_cache_path path [levels=number] keys_zone=zone_name:zone_size [inactive=time][max_size=size]; |
|---|---|
| 默认值 | —— |
| 位置 | http |
- path:缓存路径存放地址
- levels:指定缓存空间对应的目录,可设置 3 层,每层取 1 或 2。例如
levels=1:2表示两层(第一次一个字母,第二次两个);levels=1:2:2对应/usr/local/proxy_cache/d/20/d3。 - keys_zone:指定名称和大小,如
keys_zone=itcast:200m - inactive:指定缓存数据多长时间未被访问就会删除,如
inactive=1d(1 天) - max_size:设置最大缓存空间,如
max_size=20g
proxy_cache_path /usr/local/proxy_cache levels=1:2 keys_zone=richu:200m inactive=1d max_size=20g;
12.2 proxy_cache
开启或关闭代理缓存。
| 语法 | proxy_cache off | on |
|---|---|
| 默认值 | proxy_cache off |
| 位置 | http、server、location |
12.3 proxy_cache_key
设置 web 缓存的 key 值,Nginx 会根据 key 值 MD5 哈希缓存。
| 语法 | proxy_cache_key key |
|---|---|
| 默认值 | proxy_cache_key $scheme$proxy_host$request_uri |
| 位置 | http、server、location |
12.4 proxy_cache_valid
对不同状态码的 URL 设置不同的缓存时间。
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 1m;
# 200 302 缓存十分钟 404 缓存 1 分钟
12.5 proxy_cache_min_uses
设置资源被访问多少次之后被缓存。
| 语法 | proxy_cache_min_uses number; |
|---|---|
| 默认值 | proxy_cache_min_uses 1 |
| 位置 | http、server、location |
12.6 proxy_cache_method
缓存哪些 HTTP 方法。
| 语法 | proxy_cache_method GET|HEAD|POST |
|---|---|
| 默认值 | proxy_cache_method GET HEAD; |
| 位置 | http、server、location |
12.7 缓存清除(ngx_cache_purge)
- 删除资源文件夹:
rm -rf /usr/local/proxy_cache - 安装第三方模块:
tar -zxf ngx_cache_purge-2.3.tar.gz
mv ngx_cache_purge-2.3 purge
--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/
nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/
local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/
logs/error.log --http-log-path=/usr/local/nginx/logs/access.log
--pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/
nginx/logs/nginx.lock --with-http_gzip_static_module
--with-http_ssl_module --add-module=/root/nginx/module/
fair --with-stream
./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/
sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/
usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/
logs/error.log --http-log-path=/usr/local/nginx/logs/access.log
--pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/
nginx/logs/nginx.lock --with-http_gzip_static_module
--with-http_ssl_module --add-module=/root/nginx/module/
fair --with-stream --add-module=/root/nginx/module/purge
make
mv nginx nginxold
cp nginx /usr/local/nginx/sbin
make upgrade
使用清除:
location ~ /purge(/.*) {
proxy_cache_purge richu
(proxy_cache指定的名称) richu
(proxy_cache_key指定的名称)
}
13. 设置资源不缓存
13.1 proxy_no_cache
指定不缓存的条件。
| 语法 | proxy_no_cache string …; |
|---|---|
| 默认值 | —– |
| 位置 | http、server、location |
13.2 proxy_cache_bypass
不从缓存中获取数据。只要有 1 个不为 0 或不为空则成立。
| 语法 | proxy_cache_bypass string; |
|---|---|
| 默认值 | —– |
| 位置 | http、server、location |
13.3 常用变量
$cookie_nocache:当前请求 cookie 中键为 nocache 对应的值$arg_nocache、$arg_comment:当前请求参数中属性名为 nocache、comment 对应的值
13.4 动静分离
- 动:后台应用程序的业务处理
- 静:网站的静态资源(html、javascript、css、images 等文件)
将 war 包放入 Tomcat 的 webapps 目录下。
14. Keepalived 安装与高可用
14.1 配置安装
- 下载:Keepalived for Linux
- 解压缩:
tar -zxf keepalives.tar.gz - 配置:
./configure --sysconf=/etc --prefix=/usr/local - 编译安装:
make && make install
配置文件:
/etc/keepalived/keepalived.conf;二进制启动文件:/usr/local/sbin
配置文件示例:
global_defs {
notification_email { #出问题会给下面的邮件发送消息
acassen@firewall.loc
failover@firewall.loc
sysadmin@firewall.loc
}
#从哪个邮件发送消息
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id LVS_DEVEL #唯一标识
vrrp_skip_check_adv_addr
vrrp_strict
vrrp_garp_interval 0
vrrp_gna_interval 0
}
vrrp_instance VI_1 {
state MASTER #主
interface eth0 #网卡名称
virtual_router_id 51
priority 100 #指定优先级
advert_int 1 #发送健康状况的时间间隔
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.200.16
192.168.200.17
192.168.200.18
}
14.2 vrrp_script 健康检查
自动判断 Nginx 服务的状况:
vrrp_scipt 脚本名称
{
script "脚本位置"
interval 3 #执行时间间隔
weight -20 #动态调整vrrp_instance的优先级
}
#!/bin/bash
num=`ps -C nginx --no-header | wc -l`
if [$num -eq 0];then
/usr/local/nginx/sbin/nginx
sleep 2
if [`ps -C nginx --no-header | wc -l ` -eq 0];then
kill keepalived
fi
fi
15. 制作下载站点
使用 ngx_http_autoindex_module 模块。
(1) autoindex:启用或禁用目录列表输出。
| 语法 | autoindex on|off |
|---|---|
| 默认值 | autoindex off |
| 位置 | http、server、location |
(2) autoindex_exact_size:对应 HTML 格式,指定是否在目录列表展示文件的详细大小。
| 语法 | autoindex_exact_size on | off |
|---|---|
| 默认值 | autoindex_exact_size on |
| 位置 | http、server、location |
(3) autoindex_format:设置目录列表的格式。
| 语法 | autoindex_format html|xml|json|jsonp |
|---|---|
| 默认值 | autoindex_format html |
| 位置 | http、server、location |
(4) autoindex_localtime:对应 HTML 格式,是否在目录列表上显示时间。
| 语法 | autoindex_localtime on |off |
|---|---|
| 默认值 | autoindex_localtime off |
| 位置 | http、server、location |
配置示例:
location /download{
root /usr/local/download;
autoindex on;
autoindex_exact_size on;
autoindex_format html;
autoindex_localtime on;
}
16. Nginx 用户认证
使用 ngx_http_auth_basic_module 模块。
(1) auth_basic:使用“HTTP 基本认证”协议启用用户名和密码的验证。
| 语法 | auth_basic on |off |
|---|---|
| 默认值 | auth_basic off |
| 位置 | http、server、location、limit_except |
(2) auth_basic_user_file:指定用户名和密码文件所在位置。
| 语法 | auth_basic_user_file file |
|---|---|
| 默认值 | —– |
| 位置 | http、server、location、limit_except |
auth_basic 'please input your password'
auth_basic_user_file htpassword
使用工具生成密码(yum install -y httpd-tools):
htpasswd -c /usr/local/nginx/conf/htpasswd name //生成新文件和密码
htpasswd -b /usr/local/nginx/conf/htpasswd name password //追加密码
htpasswd -D /usr/local/nginx/conf/htpasswd name //删除指定用户名
htpasswd -v /usr/local/nginx/conf/htpasswd name //验证密码
一句话总结:Nginx 以事件驱动的单 Master 多 Worker 架构,通过反向代理、负载均衡、静态资源优化、缓存、SSL 与 Rewrite 等模块,成为支撑高并发 Web 服务与网关的核心组件。