实验前期准备:
两台Nginx真实服务器;
Server:192.168.139.100
Proxy:192.168.139.153
Server作为网站主目录,Proxy作为方向代理服务器;
实验所用到的模块 ngx_http_proxy_module。
安装Nginx
yum install yum-utils
vim /etc/yum.repos.d/nginx.repo
将下面代码写入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
[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
yum-config-manager --enable nginx-mainline
yum install nginx -y //安装nginx
nginx -v
nginx version: nginx/1.15.8
配置网站主服务器
为了方便观察效果,这里更改了nginx默认的主页。

[root@Server ~]# cat /usr/share/nginx/html/index.html //查看网页
<img src='1.jpg'/>
[root@Server ~]# ls /usr/share/nginx/html/
101.html 1.jpg 50x.html index.html
配置代理服务器
首先确认代理服务器的Nginx主页面

接下来配置Nginx的默认主页
加入ngx_http_proxy_module代理模块
vim /etc/nginx/conf.d/default.conf
location / {
proxy_pass http://192.168.139.100:80; 代理真实服务器IP
proxy_redirect default; 如果真实服务器使用的是真实IP,非默认端口,则改成默认端口。
proxy_set_header Host $http_host; 重新定义或者添加发往后端服务器的请求头
proxy_set_header X-Real-IP $remote_addr; 记录客户端真实IP,否则日志中显示的是代理服务器的IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 记录代理服务器IP
proxy_connect_timeout 30; 后端服务器连接的超时时间
proxy_send_timeout 60; 规定后端服务器传回所有数据的时间
proxy_read_timeout 60; 接收真实服务器数据超时时间,默认是
proxy_buffering on; 开启缓存功能
proxy_buffer_size 32k; 响应头的缓冲区大小
proxy_buffers 4 128k; 内存缓冲区大小
proxy_busy_buffers_size 256k; 从proxy_buffers拿出一部分缓冲区来专门向客户端传递数据的地方
proxy_max_temp_file_size 256k; 超大的响应头存储文件
}
systemctl restart nginx
测试代理服务器

查看日志确认代理信息

配置代理服务器的缓存功能
vim /etc/nginx/nginx.conf
http {
proxy_cache_path /nginx_cache/nginx/cache levels=1:2 keys_zone=proxy_cache:10m max_size=10g inactive=60m use_temp_path=off;
}
准备缓存文件的存放目录
mkdir -p /nginx_cache/nginx/cache
vim /etc/nginx/conf.d/default.conf
location / {
proxy_cache proxy_cache;
proxy_cache_valid 200 304 12h;
proxy_cache_valid any 10m;
proxy_cache_key $host$uri$is_args$args;
add_header Nginx-Cache "$upstream_cache_status";
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
}
systemctl restart nginx
查看日志访问状态,并再次访问代理服务器查看网站

在图中可以看到,代理服务器已经成功代理。
查看缓存目录
[root@Nginx ~]# ls /nginx_cache/nginx/cache/
5 e
已经成功创建缓存文件
观察日志并再次访问代理服务器

网友评论