Nginx端口转发反向代理负载均衡

最近做nginx方面的优化,想到了用反向代理的方式,因为只有一台机子,所以就用多个端口转发了。
1. 安装nginx,看官网就可以
2. vim /etc/nginx/nginx.conf

http {  
    ......
    #site 是名称
   upstream site{
        server 127.0.0.1:8001;
        server 127.0.0.1:8002;
        #如果是多台机子,可以如下配置
        #server 192.1681.100;
        #server 192.168.1.101;
        #使用其它端口
        #server ip:端口号
   }
   server {
        #访问URL
        server_name load.com;
       #用户访问为80端口
        listen 80;
        location / {
              #代理名称
                proxy_pass         http://site;
                proxy_set_header   Host             $host;
                proxy_set_header   X-Real-IP        $remote_addr;
                proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
   }
    include vhost/*.conf;
}
以上nginx.conf的主配置,因为使用vhost,所以详细配置在vhost里建立了两个

load1.com.conf
load2.com.conf

vim load1.com.conf  
server  
{
    listen 8001;
    root /opt/www/test;
    access_log /opt/logs/test.com_access.log;
    error_log /opt/logs/test.com_error.log;
    location / {
        index  index.html index.htm index.php ;
    }
    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}
vim load2.com.conf  
server  
{
    listen 8002;
    root /opt/www/test;
    access_log /opt/logs/test.com_access.log;
    error_log /opt/logs/test.com_error.log;
    location / {
        index  index.html index.htm index.php ;
    }
    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

执行 nginx -s reload 重新加载
绑定host,假设本地ip为192.168.1.99
192.168.1.99 load.com

浏览器访问load.com,查看返回结果,请求结果会自动切换

如果需要多个upstream,多个域名对应,则再添加一条规则
upstream sitelocal{  
        server 172.16.3.62;
        server 172.16.3.63:81;
 }
server {  
        server_name load-local.com;
        listen 80;
        location / {
         proxy_pass         http://sitelocal;
         proxy_set_header   Host             $host;
         proxy_set_header   X-Real-IP        $remote_addr;
         proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
 }

郝先生

继续阅读此作者的更多文章