1. 程式人生 > >centos7.4 搭建nginx反向緩存代理

centos7.4 搭建nginx反向緩存代理

nginx反向代理

nginx可以實現基於硬盤緩存的反向代理服務
通過proxy_cache和fastcgi_cache兩個功能模塊完成配置


-----

本例:
nginx反向代理服務器192.168.80.81
web服務器192.168.80.82
win7客戶機 192.168.80.79


-----
### web服務器192.168.80.82 配置:
安裝簡單的httpd,提供web服務即可


-----
### nginx反向代理服務器192.168.80.81配置:
1.上傳反向代理插件、軟件和解壓:
tar xzvf ngx_cache_purge-2.3.tar.gz -C /opt/
tar xzvf pcre-8.41.tar.bz2 -C /opt/

tar xzvf nginx-1.13.5.tar.gz -C /opt/
yum install -y zlib-devel


2.編譯安裝nginx
cd /opt/nginx-1.13.5

./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module \
--with-pcre=/opt/pcre-8.41 \
--add-module=/opt/ngx_cache_purge-2.3

make && make intall

useradd -M nginx

cd /usr/local/nginx/conf

vi nginx.conf

清除原內容,插入以下:
user nginx nginx;
worker_processes 1;
error_log logs/error.log crit;
worker_rlimit_nofile 65535;
events {
use epoll;
worker_connections 65535;
}
http {
include mime.types;
default_type application/octet-stream;
charset utf-8;
#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;
sendfile on;
tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
tcp_nodelay on;
client_body_buffer_size 512k;
proxy_connect_timeout 5;
proxy_read_timeout 60;
proxy_send_timeout 5;
proxy_buffer_size 16k;
proxy_buffers 4 64k;
proxy_busy_buffers_size 128k;
proxy_temp_file_write_size 128k;
proxy_temp_path /var/cache/nginx/cache_temp;
proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
upstream backend_server{
server 192.168.80.185:80 weight=1 max_fails=2 fail_timeout=30s;
}
#gzip on;
server {
listen 80;
server_name test 192.168.80.81;
index index.html index.htm;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_cache cache_one;
proxy_cache_valid 200 304 12h;
proxy_cache_key $host$uri$is_args$args;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://backend_server;
expires 1d;
}
location ~/purge(/.*) {
allow 127.0.0.1;
allow 192.168.80.0/24;
deny all;
proxy_cache_purge cache_one $host$1$is_args$args;
}
location ~\.(php|jsp|cgi)?$ {
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://backend_server;
}
access_log off;
}
}

3.啟動nginx
創建緩存目錄
mkdir -p /var/cache/nginx/cache_temp
mkdir /var/cache/nginx/proxy_cache

ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
nginx -t 檢查配置文件
nginx
netstat -anpt | grep nginx

service firewalld stop
setenforce 0


測試

驗證代理:win7客戶機80.79訪問nginx反向代理服務器地址80.81
可以看到web服務器80.82內容

驗證緩存:在nginx反向代理服務器192.168.80.81上

ls /var/cache/nginx/proxy_cache //使TAB鍵向後補全文件夾,可以驗證1位文件夾名下的兩位文件夾名下的緩存文件

http://192.168.80.81/purge/ //用來清除緩存。

ls /var/cache/nginx/proxy_cache/ //使TAB鍵向後補就補不全了



centos7.4 搭建nginx反向緩存代理