适配 /etc/nginx(yum 安装版)
环境:
代理缓存服务器:
192.168.42.145(nginx 配置目录/etc/nginx)源站服务器:
192.168.42.162yum 安装 Nginx,配置文件:/etc/nginx/nginx.conf
一、环境检查(两台机器都执行)
1. 检查 Nginx 是否安装
nginx -v
- 输出版本号 → 已安装
- command not found → 安装:
yum install nginx -y
2. 防火墙、SELinux(两台都操作)
# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld
# 关闭SELinux
setenforce 0
sed -i 's/^SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
保证两台机器互相 ping 通,80 端口放行
3. 时间同步(实验可选)
yum install chrony -y
systemctl start chronyd
systemctl enable chronyd
二、代理服务器(192.168.42.145)配置
步骤 1:创建缓存目录(同分区!)
bash
mkdir -p /home/proxy_temp_dir
mkdir -p /home/proxy_cache_dir
# 修改属主为nginx
chown nginx:nginx -R /home/proxy_temp_dir /home/proxy_cache_dir
chmod -R 777 /home/proxy_temp_dir /home/proxy_cache_dir
步骤 2:编辑主配置文件 /etc/nginx/nginx.conf
打开配置:
vim /etc/nginx/nginx.conf
在http {} 大括号内部添加缓存全局配置:
bash
#代理临时目录
proxy_temp_path /home/proxy_temp_dir;
#Web缓存目录和参数设置
proxy_cache_path /home/proxy_cache_dir levels=1:2 keys_zone=cache_one:50m inactive=1m max_size=500m;
往下找到 server {} 块,修改为下面内容:
bash
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# 增加响应头,查看缓存状态
add_header X-Via $server_addr;
add_header X-Cache $upstream_cache_status;
location / {
proxy_cache cache_one;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_valid 200 10m;
proxy_cache_valid 304 1m;
proxy_cache_valid 301 302 1h;
proxy_cache_valid any 1m;
# 反向代理指向源站IP
proxy_pass http://192.168.42.162;
}
}
步骤 3:校验配置 + 重启 nginx
bash
# 语法检查(重点!报错就回去改配置)
nginx -t
# 重启服务
systemctl restart nginx
# 设置开机自启(可选)
systemctl enable nginx
三、源站服务器(192.168.42.162)配置(yum 版 nginx)
步骤 1:启动 nginx
bash
systemctl start nginx
systemctl enable nginx
yum 安装的默认网页根目录:/usr/share/nginx/html
步骤 2:新建测试页面
vim /usr/share/nginx/html/test.html
写入:
<h1>This is proxy_cache test page from source site 192.168.42.162!</h1>
保存退出。
自测源站(可选)
访问 http://192.168.42.162/test.html,确认页面正常打开。
四、缓存测试验证
- 浏览器访问代理:
http://192.168.42.145/test.html - F12 → 网络 → 选中 test.html,看响应头:
- 第一次访问:
X-Cache: MISS(未命中,去源站拉取并写入缓存) - 普通刷新:
X-Cache: HIT(缓存命中,直接读本地缓存)
- 第一次访问:
⚠️ Ctrl+F5 强制刷新会绕过缓存,一直 MISS
常见报错提醒(适配 yum 版 nginx)
- 目录权限:nginx 进程用户是
nginx,缓存目录属主必须是 nginx proxy_temp_path和proxy_cache_dir必须在同一个分区(这里都在 /home,满足)/etc/nginx/conf.d/*.conf会被 include 加载,如果 conf.d 里有其他 server 块,注意端口冲突- 配置写错,
nginx -t会直接提示哪一行出错