在location指令中使用proxy_pass可以将请求代理到指定的服务器
location /forum{
proxy_pass http://192.168.0.222/bbs/;
}
当访问http://192.168.0.221/forum路径的时候将访问的是http://192.168.0.222/bbs下内容。
http://192.168.0.221/forum/index.html-->http://192.168.0.222/bbs/index.html。
location ~* ^/forum 这里如是使用正则匹配,那么proxy_pass只能指到:http://192.168.0.222/
那么以/forum开头的路径都将被转发到192.168.0.222/下:
如果访问http://192.168.0.221/forum/index.html 将被转发到http://192.168.0.222/index.html。
nginx默认转发时,客户端IP都是nginx服务器IP
配置转发时设置真实客户端IP:
location /forum{
proxy_pass http://192.168.0.222/bbs/;
proxy_set_header X-Real-IP $remote_addr;
}
只需使用proxy_set_header指令 使用X-Real-IP $remote_addr为nginx服务器变量,可以取得客户端IP。
将请求分发至一组服务器,做负载均衡:
upstream httpd{
server 192.168.0.222 weight=1;
server 192.168.0.223 weight=1;
}
使用upstream 指令(在http指令里面,server指令外面)使用server来指定一个服务器地址,不能加http://,weight可以指定权重。
在location里指定prox_pass指定转发至这组服务器(upstream)即可:
server{
......
location /{
proxy_pass http://httpd/;
proxy_set_header X-Real-IP $remote_addr;
}
}
实现后端服务器健康状况检查:
upstream httpd{
server 192.168.0.222 weight=1 max_fails=2 fail_timeout=3;
server 192.168.0.223 weight=1 max_fails=2 fail_timeout=3;
}
max_fails指定最多失败次数,fail_timeout失败超时时间为3秒,关闭其中一台server之后会发现所有转发都会到另一台服务器上。
再启动也会轮训转发。
配置实现nginx的备份节点
当指定服务器都不可时会转发到此服务器上
server{
listen 8080;
server_name localhost;
root /var/backup;
}
upstream httpd{
ip_hash; # 使用源地址HASH做持久连接,支持least_conn,random-rand,ip_hash三种
server 192.168.0.222 weight=1 max_fails=2 fail_timeout=3;
server 192.168.0.223 weight=1 max_fails=2 fail_timeout=3;
server 127.0.0.1:8080 backup;
}
nginx的分发算法
支持ip_hash(源IP)、least_conn(最少连接)、random-rand(随机)
upstream httpd{
ip_hash; # 使用源地址HASH做持久连接,支持least_conn,random-rand,ip_hash三种
server 192.168.0.222 weight=1 max_fails=2 fail_timeout=3;
server 192.168.0.223 weight=1 max_fails=2 fail_timeout=3;
# server 127.0.0.1:8080 backup; 使用ip_hash不能使用backup
}
nginx proxy_cache缓存
http上下文中配置:
proxy_cache_path /var/nginx/cache/first levels=1:2:1 keys_zone=first:20m max_size=1G;
location上下文中使用cache
location / {
proxy_pass http://httpd;
proxy_cache cache_one;
}
使用proxy_cache指定来使用缓存,要指定花黁的keys_zone,为定义proxy_cache_path时的keys_zone。