編譯安裝nginx并實現反向代理負載均衡和緩存功能

一、編譯安裝nginx

1、下載

[root@ns1 ~]# wget http://nginx.org/download/nginx-1.10.0.tar.gz

2、解壓

[root@ns1 ~]# tar xf nginx-1.10.0.tar.gz
[root@ns1 ~]# cd nginx-1.10.0

3、安裝依賴組件

[root@ns1 nginx-1.10.0]# yum install pcre-devel    #url重寫需要的組件
[root@ns1 nginx-1.10.0]# yum install zlib-devel    #gzip所依賴組件
[root@ns1 nginx-1.10.0]# yum install openssl-devel        #openssl依賴的組件
[root@ns1 nginx-1.10.0]# groupadd -r nginx           #創建一個nginx系統組
[root@ns1 nginx-1.10.0]# useradd -g nginx -r nginx   #在nginx組中加入nginx用戶
[root@ns1 nginx-1.10.0]# id nginx
uid=996(nginx) gid=994(nginx) 組=994(nginx

4、編譯安裝

【注意】因為nginx部分模塊不支持動態加載,所以需要什么模塊一定要提前指定好,淘寶的tengine則支持動態加載模塊。

[root@ns1 nginx-1.10.0]# ./configure --prefix=/usr/local/nginx --conf-path=/etc/nginx/nginx.conf --user=nginx --group=nginx --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 --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_flv_module --with-http_mp4_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/fastcgi --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi
[root@ns1 nginx-1.10.0]# mkdir -pv /var/tmp/nginx/{client,proxy,fastcgi,uwsgi}
[root@ns1 nginx-1.10.0]# make && make install

5、./configure選項說明

[root@ns1 nginx-1.10.0]# ./configure --help

  --help                             print this message            #幫助

  --prefix=PATH                      set installation prefix        #安裝路徑
  --sbin-path=PATH                   set nginx binary pathname        #主程序安裝路徑
  --modules-path=PATH                set modules path                #模塊安裝路徑
  --conf-path=PATH                   set nginx.conf pathname        #主配置文件安裝路徑
  --error-log-path=PATH              set error log pathname        #錯誤日志路徑
  --pid-path=PATH                    set nginx.pid pathname        #pid文件路徑
  --lock-path=PATH                   set nginx.lock pathname        #鎖文件路徑

  --user=USER                        set non-privileged user for    #nginx啟動時work進程以什么身份運行
                                     worker processes
  --group=GROUP                      set non-privileged group for    #nginx啟動時work進程以什么組運行
                                     worker processes

  --build=NAME                       set build name             #指定編譯的名稱
  --builddir=DIR                     set build directory        #指定編譯的目錄
                                                                     #with的是默認沒啟用的模塊,with后啟用
                                                                     #without的是默認啟動的模塊,without后關閉
  --with-select_module               enable select module            #開起select模塊
  --without-select_module            disable select module           #關閉select模塊
  --with-poll_module                 enable poll module              #開起poll模塊
  --without-poll_module              disable poll module             #關閉poll模塊

  --with-threads                     enable thread pool support        #啟用線程池

  --with-file-aio                    enable file AIO support        #開起文件AIO功能,一般用來提高圖片站讀i/o操作
  --with-ipv6                        enable IPv6 support                #開起ipv6支持

  --with-http_ssl_module             enable ngx_http_ssl_module        #啟用ssl模塊
  --with-http_v2_module              enable ngx_http_v2_module        #源自spdy協議,優先請求瀏覽器最繼續的內容
  --with-http_realip_module          enable ngx_http_realip_module    #反向代理時把真實訪問ip傳給后端
  --with-http_addition_module        enable ngx_http_addition_module    #在頁面后添加文本
  --with-http_xslt_module            enable ngx_http_xslt_module        #在響應XML文件時,轉為一個或多個XSLT樣式
  --with-http_xslt_module=dynamic    enable dynamic ngx_http_xslt_module    #動態的xslt模塊
  --with-http_image_filter_module    enable ngx_http_image_filter_module    #開啟圖片轉換功能,依賴 libgd 庫,能夠對圖片進行轉換格式,尺寸等
  
  --with-http_image_filter_module=dynamic        #動態的image_filter模塊
                                     enable dynamic ngx_http_image_filter_module
  --with-http_geoip_module           enable ngx_http_geoip_module    #開啟GeoIP功能,需要geoIP 數據庫的支持
  --with-http_geoip_module=dynamic   enable dynamic ngx_http_geoip_module    #動態geoip模塊
  --with-http_sub_module             enable ngx_http_sub_module            #sub模塊,用來替換相應包指定內容
  --with-http_dav_module             enable ngx_http_dav_module            #開啟WebDAV功能,此方法可以開啟PUT、DELETE、COPY、MKCOL、MOVE等HTTP方法,建議關閉
  
  --with-http_flv_module             enable ngx_http_flv_module            #流媒體模塊
  --with-http_mp4_module             enable ngx_http_mp4_module            #mp4模塊
  --with-http_gunzip_module          enable ngx_http_gunzip_module    #開啟gzip方式傳輸模式,能夠大大減少帶寬消耗
  --with-http_gzip_static_module     enable ngx_http_gzip_static_module    #壓縮靜態頁面的gizp模塊
  --with-http_auth_request_module    enable ngx_http_auth_request_module   #基于請求的返回結果來控制用戶鑒權
  --with-http_random_index_module    enable ngx_http_random_index_module   #響應用戶以 “/” 結尾的請求,并在該目錄下隨機選擇一個文件作為index文件。此模塊先于 ngx_http_index_module 被執行
  
  --with-http_secure_link_module     enable ngx_http_secure_link_module    #開啟安全鏈接功能。防盜鏈用
  --with-http_degradation_module     enable ngx_http_degradation_module    #內存不足時,Nginx將返回204或444給客戶端
  --with-http_slice_module           enable ngx_http_slice_module        #開啟切片模塊,對大文件切片用
  --with-http_stub_status_module     enable ngx_http_stub_status_module    #nginx狀態頁面模塊

  --without-http_charset_module      disable ngx_http_charset_module    #下面都是默認安裝的模塊,有需要可以關閉
  --without-http_gzip_module         disable ngx_http_gzip_module
  --without-http_ssi_module          disable ngx_http_ssi_module
  --without-http_userid_module       disable ngx_http_userid_module
  --without-http_access_module       disable ngx_http_access_module
  --without-http_auth_basic_module   disable ngx_http_auth_basic_module
  --without-http_autoindex_module    disable ngx_http_autoindex_module
  --without-http_geo_module          disable ngx_http_geo_module
  --without-http_map_module          disable ngx_http_map_module
  --without-http_split_clients_module disable ngx_http_split_clients_module
  --without-http_referer_module      disable ngx_http_referer_module
  --without-http_rewrite_module      disable ngx_http_rewrite_module
  --without-http_proxy_module        disable ngx_http_proxy_module
  --without-http_fastcgi_module      disable ngx_http_fastcgi_module
  --without-http_uwsgi_module        disable ngx_http_uwsgi_module
  --without-http_scgi_module         disable ngx_http_scgi_module
  --without-http_memcached_module    disable ngx_http_memcached_module
  --without-http_limit_conn_module   disable ngx_http_limit_conn_module
  --without-http_limit_req_module    disable ngx_http_limit_req_module
  --without-http_empty_gif_module    disable ngx_http_empty_gif_module
  --without-http_browser_module      disable ngx_http_browser_module
  --without-http_upstream_hash_module
                                     disable ngx_http_upstream_hash_module
  --without-http_upstream_ip_hash_module
                                     disable ngx_http_upstream_ip_hash_module
  --without-http_upstream_least_conn_module
                                     disable ngx_http_upstream_least_conn_module
  --without-http_upstream_keepalive_module
                                     disable ngx_http_upstream_keepalive_module
  --without-http_upstream_zone_module
                                     disable ngx_http_upstream_zone_module

  --with-http_perl_module            enable ngx_http_perl_module    #開起perl模塊
  --with-http_perl_module=dynamic    enable dynamic ngx_http_perl_module    #動態perl模塊
  --with-perl_modules_path=PATH      set Perl modules path
  --with-perl=PATH                   set perl binary pathname

  --http-log-path=PATH               set http access log pathname    #訪問日志路徑
  --http-client-body-temp-path=PATH  set path to store                #客戶端上傳內容臨時存放位置,路徑不存在則必須先創建
                                     http client request body temporary files
  --http-proxy-temp-path=PATH        set path to store                #作為代理服務器代理內容臨時存放位置
                                     http proxy temporary files
  --http-fastcgi-temp-path=PATH      set path to store                #fastcgi協議工作時所需臨時目錄
                                     http fastcgi temporary files
  --http-uwsgi-temp-path=PATH        set path to store                #uwsgi協議工作時所需臨時目錄
                                     http uwsgi temporary files
  --http-scgi-temp-path=PATH         set path to store                #scgi協議工作時所需臨時目錄
                                     http scgi temporary files

  --without-http                     disable HTTP server
  --without-http-cache               disable HTTP cache

  --with-mail                        enable POP3/IMAP4/SMTP proxy module    #開起mail模塊
  --with-mail=dynamic                enable dynamic POP3/IMAP4/SMTP proxy module    #開起mail動態模塊
  --with-mail_ssl_module             enable ngx_mail_ssl_module
  --without-mail_pop3_module         disable ngx_mail_pop3_module
  --without-mail_imap_module         disable ngx_mail_imap_module
  --without-mail_smtp_module         disable ngx_mail_smtp_module

  --with-stream                      enable TCP/UDP proxy module    #stream模塊用于tcp/udp和負載均衡
  --with-stream=dynamic              enable dynamic TCP/UDP proxy module    #動態stream模塊
  --with-stream_ssl_module           enable ngx_stream_ssl_module
  --without-stream_limit_conn_module disable ngx_stream_limit_conn_module
  --without-stream_access_module     disable ngx_stream_access_module
  --without-stream_upstream_hash_module
                                     disable ngx_stream_upstream_hash_module
  --without-stream_upstream_least_conn_module
                                     disable ngx_stream_upstream_least_conn_module
  --without-stream_upstream_zone_module
                                     disable ngx_stream_upstream_zone_module

  --with-google_perftools_module     enable ngx_google_perftools_module  #內存管理模塊合理調配系統內存資源給服務器
  --with-cpp_test_module             enable ngx_cpp_test_module    #啟用ngx_cpp_test_module支持

  --add-module=PATH                  enable external module    #啟用外部模塊支持
  --add-dynamic-module=PATH          enable dynamic external module    #動態加載外部模塊

  --with-cc=PATH                     set C compiler pathname    #用于C編譯環境非默認的情況,指向C編譯器路徑
  --with-cpp=PATH                    set C preprocessor pathname    #指向C預處理路徑
  --with-cc-opt=OPTIONS              set additional C compiler options    #設置C編譯器參數
  --with-ld-opt=OPTIONS              set additional linker options    #設置連接文件參數
  --with-cpu-opt=CPU                 build for the specified CPU, valid values:    #指定編譯的CPU
                                     pentium, pentiumpro, pentium3, pentium4,
                                     athlon, opteron, sparc32, sparc64, ppc64

  --without-pcre                     disable PCRE library usage
  --with-pcre                        force PCRE library usage        #url重寫時所需模塊,有更強大的正則引擎
  --with-pcre=DIR                    set path to PCRE library sources
  --with-pcre-opt=OPTIONS            set additional build options for PCRE
  --with-pcre-jit                    build PCRE with JIT compilation support

  --with-md5=DIR                     set path to md5 library sources
  --with-md5-opt=OPTIONS             set additional build options for md5
  --with-md5-asm                     use md5 assembler sources

  --with-sha1=DIR                    set path to sha1 library sources
  --with-sha1-opt=OPTIONS            set additional build options for sha1
  --with-sha1-asm                    use sha1 assembler sources

  --with-zlib=DIR                    set path to zlib library sources    gzip
  --with-zlib-opt=OPTIONS            set additional build options for zlib
  --with-zlib-asm=CPU                use zlib assembler sources optimized
                                     for the specified CPU, valid values:
                                     pentium, pentiumpro

  --with-libatomic                   force libatomic_ops library usage
  --with-libatomic=DIR               set path to libatomic_ops library sources

  --with-openssl=DIR                 set path to OpenSSL library sources        #openssl所在位置
  --with-openssl-opt=OPTIONS         set additional build options for OpenSSL

  --with-debug                       enable debug logging

二、啟動腳本

[root@ns1 init.d]# vim /etc/init.d/nginx    #編寫啟動腳本
#! /bin/bash
#
# 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
# pidfile:     /var/run/nginx/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/usr/local/nginx/sbin/nginx"    #根據自己的安裝位置修改這里
prog=$(basename $nginx)

NGINX_CONF_FILE="/etc/nginx/nginx.conf"    #修改這里

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/nginx.lock    #修改這里

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    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
                        
[root@localhost nginx-1.10.0]# chmod 755 /etc/init.d/nginx
[root@localhost nginx-1.10.0]# service nginx restart
#開機啟動
[root@localhost nginx-1.10.0]# chkconfig --add nginx
[root@localhost nginx-1.10.0]# chkconfig nginx on
[root@localhost nginx-1.10.0]# chkconfig --list nginx
nginx          	0:關	1:關	2:開	3:開	4:開	5:開	6:關

三、配置2個基于nginx的web

(172.16.22.39)(172.16.22.40)

[root@ns2 ~]# vim /etc/nginx/nginx.conf
user  nginx;    #以哪個用戶的身份運行nginx
worker_processes  1;    #運行幾個worker進程

error_log  /var/log/nginx/error.log;    #錯誤日志位置
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        /var/run/nginx/nginx.pid;    #pid文件位置


events {
    worker_connections  1024;    #一個worker進程的最大并發數量
}


http {
    include       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  /var/log/nginx/access.log  main;    #訪問日志位置和應用上面的格式

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;        #持久連接時間

    gzip  on;                #開起gzip壓縮

    server {
        listen       80;
        server_name  ns3.xinfeng.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /var/www/html;    #根目錄位置
            index  index.html index.htm;    #首頁索引文件
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;        #錯誤頁面位置
        location = /50x.html {
            root   html;
        }
}
[root@ns2 ~]# vim /var/www/html/index.html
<h1>ns2.xinfeng.com</h1>
[root@ns2 ~]# service nginx start


[root@ns3 ~]# vim /var/www/html/index.html
<h1>ns3.xinfeng.com</h1>
[root@ns3 ~]# vim /var/www/html/ds.html
<h1>There is ds.</h1>
[root@ns3 ~]# service nginx start

四、配置反向代理,負載均衡,緩存

1、創建緩存目錄和修改hosts文件(172.16.22.38)

#創建緩存目錄(172.16.22.38),修改hosts文件(全部主機)
[root@ns1 ~]# mkdir -pv /cache/nginx
[root@ns1 ~]# chown nginx:nginx /cache/nginx
[root@ns1 ~]# vim /etc/hosts
172.16.22.38    ns1.xinfeng.com
172.16.22.39    ns2.xinfeng.com
172.16.22.40    ns3.xinfeng.com
#另外兩臺也要修改

2、修改代理服務器配置文件(172.16.22.38)

[root@ns1 ~]# vim /etc/nginx/nginx.conf
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log error;

pid        /var/run/nginx/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       /etc/nginx/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  /var/log/nginx/access.log  main;

    proxy_cache_path /cache/nginx/ levels=1:1 keys_zone=mycache:32m;    #緩存路徑,1:1表示1級目錄下有1個子目錄,緩存key名稱為mycache后面調用時要用,緩存大小為32m

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    gzip  on;

    upstream xinfengsvr {        #定義一個負載均衡組,組名叫xinfengsvr,下面直接調用組名
        server 172.16.22.39:80 weight=1 max_fails=2 fail_timeout=1;    #權重1,錯誤2次,每次超時1秒,就算健康狀態,檢測失敗,還可以在后面街上backup將次服務器作為備用服務器
        server 172.16.22.40:80 weight=1 max_fails=2 fail_timeout=1;    #
        }

    server {
        listen       80;
        server_name  ns1.xinfeng.com;

        location / {
            root    /var/www/html;
            index    index.html index.htm;
            proxy_pass   http://xinfengsvr/;    #將對本服務器首頁的請求代理至負載均衡組xinfengsvr,以實現負載均衡
            }


        location /index/ {
            proxy_cache mycache;    #調用緩存key為mycahe
            proxy_cache_valid 200 1m;    #返回值為200的緩存1分鐘
           #root   /var/www/html;
            proxy_pass http://172.16.22.40/ds.html;    #將url為/index/的代理至ns3.xinfeng.com/ds.html
            proxy_set_header Host $host;        #把客戶端真實主機名傳遞給后端服務器
            proxy_set_header X-Real-IP $remote_addr;    #把客戶端真實ip傳遞給后端服務器
            index  index.html index.htm;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /var/www/html;
        }


    }


}

[root@ns1 ~]# service nginx reload
[root@ns1 ~]# service nginx restart

在把客戶端ip發給后端服務器時,apache需要修改httpd.conf

LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

如果是后端nginx,需要修改nginx.conf

--with-http_realip_module    #需要安裝時開起此模塊
set_real_ip_from   192.168.1.0/24;     #這里是前端代理服務器ip,可以是單個IP或者IP段
set_real_ip_from   192.168.2.1;
real_ip_header     X-Real-IP;

五、查看結果

1、查看緩存結果

[root@ns1 ~]# cd /cache/nginx
[root@ns1 ~]# ls
5
[root@ns1 ~]# ls 5/d/a9c378c70c62b5ed29dac22910c12ad5

2、負載均衡效果

nginx.gif

3、反向代理效果

blob.png

原創文章,作者:N17_信風,如若轉載,請注明出處:http://www.www58058.com/16479

(0)
N17_信風N17_信風
上一篇 2016-05-23
下一篇 2016-05-25

相關推薦

  • linux常用網絡配置

    網卡名稱:  網絡接口識別并命名相關的udev配置文件:    /etc/udev/rules.d/70-persistent-net.rules  卸載網卡驅動:    modprobe  -r e1000  裝載網卡驅動:    modprobe &nbs…

    Linux干貨 2016-09-06
  • linux 邏輯卷管理

    lvm介紹:     lvm:全稱Logical Volume Manager,重點在于可以彈性調整filesystem 容量,并非在于數據安全     lvm:整合多個分區或者磁盤為一個整體,讓分區看起來想一個整體。     lvm:設備…

    Linux干貨 2016-09-01
  • 馬哥教育網絡21期+第四周作業博客

    1、復制/etc/skel目錄為/home/tuser1,要求/home/tuser1及其內部文件的屬組和其它用戶均沒有任何訪問權限。 [root@localhost ~]# cp -r /etc/skel /home/ && mv /home/skel&nbsp…

    Linux干貨 2016-09-05
  • Linux Service and Security(Part 2)

    接PART 1 4、SSH端口轉發:SSH會自動加密和解密所有SSH客戶端與服務端之間的網絡數據。但是,SSH還能夠將其它TCP端口的網絡數據通過SSH鏈接來轉發,并且自動提供了相應的加密及解密服務,這一過程也被叫做“隧道(tunneling)”。telnet,SMTP,LDAP這些TCP應用均能夠從中得益,避免了用戶名、密碼以及隱私信息的明文傳輸。同時,如…

    Linux干貨 2016-10-09
  • bash 函數

        函數可以讓多條shell的命令組成語句塊,實現代碼重用和模塊化編程。讓我們在不用重復編寫一些腳本,下面讓我們來了解函數。 1,函數的簡介 函數在腳本中使用應先定義,聲明,再可以調用。 函數function 是由若干條shell 命令組成的語句塊,實現代碼重用和模塊化編程。 函數與shell 程序形式上是相似的,…

    Linux干貨 2016-08-24
  • lvs-dr

            通過為請求報文重新封裝一個MAC首部進行轉發,源MAC是DIP所在的接口的MAC,目標MAC是某挑選出的RS的RIP所在接口的MAC地址;源IP/PORT,以及目標IP/PORT均保持不變;     VIP通常配置在lo:0…

    2017-06-29

評論列表(3條)

  • kattall
    kattall 2016-05-26 11:16

    我第一次在/cache/nginx/里面有,但是我刪除下面的緩存之后,為什么就不生成了?

    • N17_信風
      N17_信風 2016-05-28 14:55

      @Net20_赤羽緩存大小是多少,緩存時長是多少?文件權限有沒有變化?

    • Net20_赤羽
      Net20_赤羽 2016-06-01 14:05

      @N17_信風必須得訪問/index 這個才會生成緩存。有點明白了

欧美性久久久久