Nginx反向代理+負載均衡

Nginx反向代理+負載均衡

1     環境

1.centos 6.5

2.nginx-1.9.2.tar.gz

3.pcre-8.32.tar.gz 

2     安裝Nginx

三臺服務器都做進行的操作:

 

2.1   安裝pcre

 

1.tar zxf pcre-8.32.tar.gz

2.cd pcre-8.30/

3../configure

4.make && make install

5.cd ../

6.安裝pcre庫是爲了兼容nginx rewrite當時我安裝的時候沒有安裝pcre,在做nginx重定向的時候死活出不來,我還以爲是我的重定向的問題,最後纔想起了是pcre沒有安裝,你們要注意哦!!

 

2.2    安裝nginx

 

1、解壓

tar xf  nginx-1.9.2.tar.gz

2、新建nginx用戶與組

groupadd-g 108  -r nginx

useradd-u 108 -r -g 108 nginx

idnginx   查看nginxID

3、備編譯配置文件

yuminstall -y pcre-devel openssl-devel

 

./configure   --prefix=/usr   --sbin-path=/usr/sbin/nginx   --conf-path=/etc/nginx/nginx.conf   --error-log-path=/var/log/nginx/error.log  --http-log-path=/var/log/nginx/access.log   --pid-path=/var/run/nginx/nginx.pid    --lock-path=/var/lock/nginx.lock   --user=nginx  --group=nginx  --with-http_ssl_module  --with-http_flv_module  --with-http_stub_status_module  --with-http_gzip_static_module  --http-client-body-temp-path=/var/tmp/nginx/client/  --http-proxy-temp-path=/var/tmp/nginx/proxy/   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/  --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi  --http-scgi-temp-path=/var/tmp/nginx/scgi   --with-pcre

 

4nginx的配置文件

vim/etc/init.d/nginx

#!/bin/sh
#
# nginx- this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
#description:  Nginx is an HTTP(S) server,HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
#processname: nginx
#config:      /etc/nginx/nginx.conf
#config:      /etc/sysconfig/nginx
#pidfile:     /var/run/nginx.pid
# Sourcefunction library.
./etc/rc.d/init.d/functions
# Sourcenetworking configuration.
./etc/sysconfig/network
# Checkthat networking is up.
["$NETWORKING" = "no" ] && exit 0
nginx="/usr/sbin/nginx"
prog=$(basename$nginx)
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
[ -f/etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
lockfile=/var/lock/subsys/nginx
make_dirs(){
   # make required directories
   user=`nginx -V 2>&1 | grep"configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   options=`$nginx -V 2>&1 | grep'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'`]; then
           value=`echo $opt | cut -d"=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating"$value
               mkdir -p $value && chown-R $user $value
           fi
       fi
   done
}
start(){
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch$lockfile
    return $retval
}
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f$lockfile
    return $retval
}
restart(){
    configtest || return $?
    stop
    sleep 1
    start
}
reload(){
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
force_reload(){
    restart
}
configtest(){
  $nginx -t -c $NGINX_CONF_FILE
}
rh_status(){
    status $prog
}
rh_status_q(){
    rh_status >/dev/null 2>&1
}
case"$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0{start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

 

5、爲此腳本賦予執行權限

chmod +x/etc/init.d/nginx

6、添加至服務管理列表,並讓其開機自動啓動

chkconfig--add nginx

chkconfignginx on

chkconfignginx --list

 

mkdir -p/var/tmp/nginx/client

servicenginx restart

 

7、查看一下端口

netstat-anput |grep :80

 

至此,nginx安裝完成,

3     配置nginx

3.1    nginx配置文件的說明

cat /etc/nginx/nginx.conf

#運行用戶
usernobody;
 
#啓動進程,通常設置成和cpu的數量相等
worker_processes  1;
 
#全局錯誤日誌定義類型,[ debug | info | notice | warn | error | crit ]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#進程文件
pidar/runinx.pid;
 
#工作模式與連接數上限
events
{
#參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
   #epoll是多路複用IO(I/O Multiplexing)中的一種方式,
    #僅用於linux2.6以上內核,可以大大提高nginx的性能
 
   #單個後臺worker process進程的最大併發鏈接數   
    worker_connections  1024;
 # 併發總數是 worker_processes 和 worker_connections 的乘積
    # 即 max_clients = worker_processes *worker_connections
    # 在設置了反向代理的情況下,max_clients = worker_processes *worker_connections / 4  爲什麼
    # 爲什麼上面反向代理要除以4,應該說是一個經驗值
    # 根據以上條件,正常情況下的Nginx Server可以應付的最大連接數爲:4 * 8000 = 32000
    # worker_connections 值的設置跟物理內存大小有關
    # 因爲併發受IO約束,max_clients的值須小於系統可以打開的最大文件數
    # 而系統可以打開的最大文件數和內存大小成正比,一般1GB內存的機器上可以打開的文件數大約是10萬左右
    # 我們來看看360M內存的VPS可以打開的文件句柄數是多少:
    # $ cat /proc/sys/fs/file-max
    # 輸出 34336
    # 32000 < 34336,即併發連接總數小於系統可以打開的文件句柄總數,這樣就在操作系統可以承受的範圍之內
    # 所以,worker_connections 的值需根據 worker_processes 進程數目和系統可以打開的最大文件總數進行適當地進行設置
    # 使得併發總數小於操作系統可以打開的最大文件數目
    # 其實質也就是根據主機的物理CPU和內存進行配置
    # 當然,理論上的併發總數可能會和實際有所偏差,因爲主機還有其他的工作進程需要消耗系統資源。
    # ulimit -SHn 65535
 
http {
         nclude mime.types; #文件擴展名與文件類型映射表
         default_type application/octet-stream;#默認文件類型
 
          #設定日誌格式
    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;
 
         #charset utf-8; #默認編碼
         server_names_hash_bucket_size 128; #服務器名字的hash表大小
         client_header_buffer_size 32k; #上傳文件大小限制
         large_client_header_buffers 4 64k; #設定請求緩
         client_max_body_size 8m; #設定請求緩
 
         sendfile on; #開啓高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對於普通應用設爲 on,如果用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。     
 
         autoindex on; #開啓目錄列表訪問,合適下載服務器,默認關閉。
         tcp_nopush on; #防止網絡阻塞  
 
#連接超時時間
                  #keepalive_timeout  0;
                  keepalive_timeout  65;#長連接超時時間,單位是秒
                  tcp_nodelay     on;
 
#FastCGI相關參數是爲了改善網站的性能:減少資源佔用,提高訪問速度。下面參數看字面意思都能理解。
         fastcgi_connect_timeout 300;
         fastcgi_send_timeout 300;
         fastcgi_read_timeout 300;
         fastcgi_buffer_size 64k;
         fastcgi_buffers 4 64k;
         fastcgi_busy_buffers_size 128k;
         fastcgi_temp_file_write_size 128k;
 
#gzip模塊設置
         gzip on; #開啓gzip壓縮輸出
         gzip_min_length 1k; #最小壓縮文件大小
         gzip_buffers 4 16k; #壓縮緩衝區
         gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)
         gzip_comp_level 2; #壓縮等級
         gzip_types text/plainapplication/x-javascript text/css application/xml;
         #壓縮類型,默認就已經包含textml,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
         gzip_vary on;
         #limit_zone crawler $binary_remote_addr10m; #開啓限制IP連接數的時候需要使用
 
#設定負載均衡的服務器列表
upstreamblog.ha97.com {
         #upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的機率越大。
         #本機上的Squid開啓3128端口
    server 192.168.8.1:3128 weight=5;
         server 192.168.80.121:80 weight=3;
         server 192.168.80.122:80 weight=2;
         server 192.168.80.123:80 weight=3;
}
 
#設定請求緩衝
    client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;
 
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
 
 
#設定虛擬主機配置
    server {
        #偵聽80端口
        listen    80;
        #定義使用 www.nginx.cn訪問
        server_name  www.nginx.cn;
 
        #定義服務器的默認網站根目錄位置
        root html;
 
        #設定本虛擬主機的訪問日誌
        access_log  logs/nginx.access.log  main;
    #默認請求
    location / {
          root  /root;      #定義服務器的默認網站根目錄位置
          index index.php index.htmlindex.htm;   #定義首頁索引文件的名稱
 
          fastcgi_pass  www.xx.com;
         fastcgi_param  SCRIPT_FILENAME  $document_root/$fastcgi_script_name;
         include /etc/nginx/fastcgi_params;
        }
   # 定義錯誤提示頁面
    error_page  500 502 503 504 /50x.html; 
        location = /50x.html {
        root  /root;
    }
 
    #靜態文件,nginx自己處理
    location ~^/(images|javascript|js|css|flash|media|static)/ {
        root /var/www/virtual/htdocs;
        #過期30天,靜態文件不怎麼更新,過期可以設大一點,如果頻繁更新,則可以設置得小一點。
        expires 30d;
 
         PHP 腳本請求全部轉發到 FastCGI處理. 使用FastCGI默認配置.      
         location ~ .*.(php|php5)?${
                  fastcgi_pass 127.0.0.1:9000;
                  fastcgi_index index.php;                 fastcgi_param  SCRIPT_FILENAME 
                  $document_root$fastcgi_script_name
                  include fastcgi.conf;
         }
         }
         #圖片緩存時間設置
         location ~.*.(gif|jpg|jpeg|png|bmp|swf)$
         {
         expires 10d;
         }
         #JS和CSS緩存時間設置
         location ~ .*.(js|css)?$
         {
         expires 1h;
         }
 
#日誌格式設定
         log_format access '$remote_addr -$remote_user [$time_local] "$request" '
                                            '$status$body_bytes_sent "$http_referer" '
                                            '"$http_user_agent"$http_x_forwarded_for';
         #定義本虛擬主機的訪問日誌
         access_log ar/loginx/ha97access.logaccess;
 
#對 "/" 啓用反向代理
         location / {
                  proxy_passhttp://127.0.0.1:88;
                  proxy_redirect off;
                  proxy_set_header X-Real-IP$remote_addr;
         #後端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
                  proxy_set_headerX-Forwarded-For $proxy_add_x_forwarded_for;
         #以下是一些反向代理的配置,可選。
                  proxy_set_header Host $host;
                  client_max_body_size 10m; #允許客戶端請求的最大單文件字節數
                  client_body_buffer_size 128k;#緩衝區代理緩衝用戶端請求的最大字節數,
                  proxy_connect_timeout 90;#nginx跟後端服務器連接超時時間(代理連接超時)
                  proxy_send_timeout 90; #後端服務器數據回傳時間(代理髮送超時)
                  proxy_read_timeout 90; #連接成功後,後端服務器響應時間(代理接收超時)
                  proxy_buffer_size 4k; #設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
                  proxy_buffers 4 32k;#proxy_buffers緩衝區,網頁平均在32k以下的設置
                  proxy_busy_buffers_size 64k; #高負荷下緩衝大小(proxy_buffers*2)
                  proxy_temp_file_write_size64k;
         #設定緩存文件夾大小,大於這個值,將從upstream服務器傳
         }
 
#設定查看Nginx狀態的地址
         location /NginxStatus {
         stub_status on;
         access_log on;
         auth_basic "NginxStatus";
         auth_basic_user_file confpasswd;
         #htpasswd文件的內容可以用apache提供的htpasswd工具來產生。
         }
 
 #禁止訪問 .htxxx 文件
            location ~ /.ht {
            deny all;
        }
#本地動靜分離反向代理配置
#所有jsp的頁面均交由tomcat或resin處理
location~ .(jsp|jspx|do)?$ {
proxy_set_headerHost $host;
proxy_set_headerX-Real-IP $remote_addr;
proxy_set_headerX-Forwarded-For $proxy_add_x_forwarded_for;
proxy_passhttp://127.0.0.1:8080;
}
#所有靜態文件由nginx直接讀取不經過tomcat或resin
location~.*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{expires 15d; }
location~ .*.(js|css)?$
{expires 1h; }
}
}

 

3.2    配置nginx反代服務器

 

cp/etc/nginx/nginx.conf /etc/nginx/nginc.conf.bak

vim nginx.conf

 

    upstream test{
        server 10.10.115.115:8080 weight=5;
        server 10.10.115.114:8080 weight=5;
 
    }
 
    server {
        listen       80;
        server_name  test.test.com;
 
        location = / {
            rewrite ^(.*)$ http://$host/test/permanent;
        }
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /test {
            index  index.jsp;
            proxy_pass      http://test/third-party-payment/;
            #limit_conn one 200;
            proxy_redirect          off;
            proxy_set_header        Host $http_host;
            proxy_set_header        X-Real-IP $remote_addr;
            proxy_set_header        X-Forwarded-For$proxy_add_x_forwarded_for;
            client_max_body_size    50m;
            client_body_buffer_size 256k;
            proxy_connect_timeout   90;
            proxy_send_timeout      90;
            proxy_read_timeout      90;
            proxy_buffer_size       256k;
            proxy_buffers           4 256k;
            proxy_busy_buffers_size 256k;
            proxy_temp_file_write_size 256k;
        }
}

 

重新啓動nginx

/etc/init.d/nginx restart

如果nginx正在使用的話就不能重新啓動,就進行重新載入。

servicenginx  reload

 

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章