今天我们利用 OpenResty 来实现一个反向代理服务器
step1:首先下载安装 OpenResty
# 下载安装 OpenResty # 默认安装在 /usr/local 目录下,可在编译时指定安装目录 # 可在编译时加入更多第三方模块,以支持更多的功能 $ wget https://openresty.org/download/openresty-1.15.8.1.tar.gz $ tar -xzvf openresty-1.15.8.1.tar.gz $ cd openresty-1.15.8.1/ $ ./configure $ make $ sudo make install
step2: 配置 OpenResty 中的 conf 文件
# 首先进入到 /usr/local/openresty/nginx 目录下,会发现这和单独安装 nginx 一样 # 打开 配置文件 $ sudo vim conf/nginx.conf
#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } 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; client_max_body_size 60M; # 【1】配置代理服务器的缓存 proxy_cache_path /tmp/nginxcache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; sendfile on; tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; #【2】加入上游服务器,如果有多台,可以使用 hash/轮询来负载均衡 # 本机只有一台服务器,就是上篇博客中使用的 nginx 搭建的 upstream local { server 127.0.0.1:8080; # server ip:port; # server ip:port; } server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; #【3】修改这部分配置文件, location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_pass http://local; #【4】使用上面设置的 cache proxy_cache my_cache; proxy_cache_key $host$uri$is_args$args; proxy_cache_valid 200 304 302 1d; #root html; #index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; }
step3: 开启反向代理服务器
# 此时在 /usr/local/openresty/nginx 目录下 $ sudo ./sbin/nginx
此时我们看一下已经开启的 nginx 服务
注释:上图观察可以发现:开启了两份 nginx 服务,一份是反向代理服务器(在 ipenresty/nginx 下开启的 nginx 服务,masterPID:43121),一份是上游的后端服务器服务(在单独安装的 nginx 下开启的 nginx 后端服务器服务,masterPID:43095)
step4: 此时我们看一下通过反向代理服务器访问页面的流程,然后抓一下包看看【该访问是在宿主机上的浏览器上输入的 IP 地址】
注1:上图可以发现:响应头是通过 openresty 代理服务器发送回来的,并不是后端的上游服务器发送回来的!另外,验证配置的反向代理服务器是否生效可以按一下步骤进行:
step1: 首先请求 反向代理服务器,同上图所示;结论:可正常显示页面
step2: 关闭上游服务器(进入 nginx 目录下执行命令:sudo ./sbin/nginx -s stop)
step3: 再次执行步骤 step1 进行访问;结论:可正常访问页面,访问的资源是上次访问的缓存
step4: 清除浏览器缓存,清除反向代理服务器缓存(配置文件中缓存的存放目录:/tmp/nginxcache 目录下),再次访问;结论:不可正常展示页面
注2:反向代理配置文件中参数的意义:
【1】
【2】
【3】
【4】
原文:https://www.cnblogs.com/zpcoding/p/11658073.html