Nginx 负载均衡简单配置

* 内网测试
本机: 127.0.0.1
VM1: 192.168.1.119:80
VM2: 192.168.1.120:80

* 代理机(127.0.0.1本机)配置
在hosts文件中添加一行 127.0.0.1 www.a.com
在http模块中添加如下代码,或者在vhosts添加引入配置文件如www.a.com

upstream www.a.com{
    server 192.168.1.119:80 weight=5;
    server 192.168.1.120:80 weight=5;
}

server {
    listen 80;
    server_name www.a.com;

    charset utf-8;
    location / {
        proxy_pass http://www.a.com;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

* 负载机配置
VM1: 192.168.1.119
VM2: 192.168.1.120

server{
    listen 80;
    server_name www.a.com;
    index index.php index.html;
    root /var/www/html;
}

配置完重启NGINX,访问www.a.com测试,weight为负载权重,刷新页面会访问不同的主机,配置成功!