Nginx1上配置proxypass, 指向Nginx2, 把请求Nginx1的流量转发到Nginx2, 返回”Welcome to Nginx2” 先修改Nginx1的nginx.conf
1 2 3 4 5 6 7 8 9
server { listen 80; server_name vod.petertest.com; include /etc/nginx/default.d/*.conf; location / { proxy_pass http://192.168.52.201; # 配置proxy_pass } # ... }
再修改Nginx2的nginx.conf
1 2 3 4 5 6 7
server { listen 80; server_name _; root /var/www/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; }
Nginx2添加一个主页
1 2
mkdir -p /var/www/html cat "Welcome to Nginx2" > /var/www/html/index.html
测试
1 2
curl 192.168.52.200:80 Welcome to nginx2
场景2: 配置多个proxypass
请求Nginx1后, Nginx1通过RR算法把请求转发给Nginx2, Nginx3
实战操作: 修改Nginx1的配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 添加upstream,和server同级 upstream my_servers{ server 192.168.52.201:80; server 192.168.52.202:80; } server { listen 80; server_name _; location / { proxy_pass http://my_servers; } # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; }
测试
1 2 3 4
# curl 192.168.52.200:80 Welcome to nginx2 # curl 192.168.52.200:80 Welcome to Nginx3
负载均衡策略
设置权重策略(weight)
修改Nginx1的配置文件,如下:
1 2 3 4
upstream my_servers { server 192.168.52.201:80 weight=4; server 192.168.52.202:80 weight=1; }
测试
1 2 3 4 5 6 7 8 9 10
# curl 192.168.52.200:80 Welcome to nginx2 # curl 192.168.52.200:80 Welcome to nginx2 # curl 192.168.52.200:80 Welcome to Nginx3 # curl 192.168.52.200:80 Welcome to nginx2 # curl 192.168.52.200:80 Welcome to nginx2
让某台服务器下线(down)
修改Nginx1的配置文件,如下:
1 2 3 4
upstream my_servers { server 192.168.52.201:80 weight=4 down; server 192.168.52.202:80 weight=1; }
测试: (Nginx2下线, 所有请求只转发到了Nginx3)
1 2 3 4
# curl 192.168.52.200:80 Welcome to Nginx3 # curl 192.168.52.200:80 Welcome to Nginx3
# curl 192.168.52.200/2.html You are on page 2 # curl 192.168.52.200/admin?page=2 You are on page 2 # curl 192.168.52.201:5000/admin?page=2 You are on page 2 # curl 192.168.52.201:5000/2.html 404 Not Found
防盗链
判断referer字段,如果不是合法的referer,返回403 修改Nginx.conf
1 2 3 4 5 6 7 8 9 10 11
server { listen 80; server_name vod.petertest.com; include /etc/nginx/default.d/*.conf; location / { valid_referers none 192.168.52.200; # referer不对, 返回403 if ($invalid_referer) { return 403; } root /www/vod; }
使用curl测试防盗链:
1 2 3 4 5 6 7 8 9
# 没有指定referer, 或referer为本机IP, 返回200 OK [root@localhost ~]# curl -I 192.168.52.200/kuangsan.png HTTP/1.1 200 OK [root@localhost ~]# curl --referer "http://192.168.52.200" -I 192.168.52.200/kuangsan.png HTTP/1.1 200 OK