nginx安裝與應用

一.nginx的安裝與啓動:javascript

1.安裝依賴庫。nginx的一些模塊須要依賴其餘第三方庫,一般有pcre庫(perl compatible regular expression,perl兼容正則表達式,支持rewrite模塊)、zlib庫(支持gzip模塊)和openssl庫(支持ssl模塊)css

yum install -y pcre pcre-devel zlib zlib-devel open openssl-develhtml

2.安裝patch前端

若是想主動檢測後端服務器狀態的話,須要用yaoweibin開發的nginx_upstream_check_module。從 https://github.com/yaoweibin/nginx_upstream_check_module 下載zip包。注意,是下載java

2.生成Makefile文件。將下載好的nginx-xxx.tar.gz上傳到centos7中,解壓,進到nginx-xxx目錄中,運行./configure,結束後會打印 nginx path prefix 路徑等信息nginx

在執行./configure命令時能夠添加一些經常使用的選項,如git

--prefix=<path> 指定nginx安裝目錄,默認爲/usr/local/nginx目錄github

--with-http_ssl_module 聲明啓用HTTP的ssl模塊,這樣nginx服務器就能夠支持HTTPS請求了web

--with-http_stub_status_module 聲明啓用Server Status頁面,默認不啓用。啓用後,只需在location塊中配置一個uri(以下文中的/nginx_status),訪問此uri頁面就能夠看到一些服務器狀態信息,正則表達式

以下

Active connections: 1

server accepts handled requests

              10          10          120

Reading: 0 Writing: 1 Waiting: 0 

--add-module=<path> 指定第三方模塊的路徑,多個第三方模塊的話就用多個--add-module指定各自的路徑。如--add-module=/home/koushengrui/app/lua-nginx-module-0.10.13 --add-module=/home/koushengrui/app/ngx_devel_kit-0.3.1rc1 --add-module=/home/koushengrui/app/nginx_upstream_check_module-master,指定編譯時添加nginx-lua-module、ngx_devel_kit和nginx_upstream_check_module(下文中的 check interval=3000 rise=2 fall=5 timeout=1000 type=tcp; 就是依賴此模塊而配置的)。

3.編譯與安裝。# make && make install。(由於涉及往/usr/local目錄中寫入,因此必須是root用戶或者具備root權限的用戶)

4.啓動與關閉。切換到/usr/local/nginx目錄,此目錄下有conf目錄、html目錄、logs目錄、sbin目錄,其中conf目錄有默認的配置文件,logs目錄有日誌文件(包括訪問日誌文件和錯誤日誌文件),sbin目錄有可執行命令

切換到sbin目錄,用默認配置文件啓動nginx:./nginx;指定配置文件啓動nginx:./nginx -c path/nginx.conf,其中path是絕對路徑,由於有時候用相對路徑不能正確解析。

nginx啓動後,就會在logs目錄中(路徑能夠在nginx.conf文件中配置,默認是logs目錄)生成一個nginx.pid的文件,記錄master process的pid。

啓動後,就能夠用nginx -s signal來控制nginx了,其中signal的值能夠是stop、quit、reload:

stop,fast shutdown  快速關閉

quit,graceful shutdown  平滑關閉。關閉nginx後,logs目錄中的nginx.pid文件會消失,下次啓動後再次生成

reload,reloading the configuration file  根據以前啓動時的配置文件平滑重啓

二.配置文件的location塊解釋

location的語法結構爲:location [=|~|~*|^~] uri

其中uri是待匹配的字符串,分爲兩種,標準uri和正則uri。[ ]中的是可選項。

nginx首先在server的多個location塊中搜索是否有標準uri和請求字符串匹配,若是有多個能夠匹配,就記錄匹配度最高的一個。而後,再按順序搜索是否有正則uri和請求字符串匹配,若是有,則結束搜索,用此location塊處理此請求。若是沒有,則使用剛纔記錄的匹配度最高的location塊處理請求。若是剛纔標準uri匹配時全部的location塊都不匹配,則此時會訪問html目錄下的index.html文件。

location = uri {

    xxx

}                     =後面跟標準uri,要求請求字符串與uri嚴格匹配。若是匹配成功,就用當前location塊處理請求,而不會繼續搜索了。

location uri {

    xxx            

}                    普通匹配,標準uri

location ~ uri {

   xxx

}                     ~後面跟正則uri,匹配時區分大小寫

location ~* uri {

   xxx

}                      ~*後面跟正則uri,匹配時不區分大小寫

location ^~ uri {

   xxx

}                      ^~後面跟標準uri,匹配以uri開頭的請求。若是匹配的話,直接用此location塊處理請求,再也不去搜索正則uri

示例:

修改默認的nginx.conf配置文件server塊以下:

server{
        listen        80;
        server_name   aliecs1;

        location /index {
                root   first;
                index  index.html;
        }
        #嚴格匹配
        location = /index {
                root  /second;
                index index.html;
        }

        location ^~ /index1 {
                root  third;
                index index.html;
        }
}

root能夠指定相對路徑,也能夠是絕對路徑。相對路徑是相對nginx的根路徑(/usr/local/nginx/),寫法是前面不加/。絕對路徑以/開始。請求地址被某個location匹配並處理後,最終訪問路徑是root指定的路徑+請求字符串去掉ip和端口的剩餘部分。

若是請求地址是192.168.153.128/index.html,則會用location /index {}處理,最終訪問/usr/local/nginx/first/index.html。

若是請求地址是192.168.153.128/index1.html,則會用location ^~ /index1 {}處理,最終訪問/usr/local/nginx/third/index1.html。

若是請求地址是192.168.153.128/index2.html,仍是會用location /index {}處理,最終訪問/usr/local/nginx/first/index2.html。

若是請求地址是192.168.153.128/index,則會用location = /index {}處理,最終訪問/second/index。

三.rewrite功能,字面意思是重寫,實際上就是重定向redirect

主要有if指令、break指令、return指令、rewrite指令、set指令:

if指令:能夠在server塊、location塊中配置,使用if作條件判斷時須要注意兩點:if與後面括號必定要有空格;判斷等因而用=,而再也不是==;表達式中的字符串不用加引號。示例:

 server {
        listen       80;
        server_name  192.168.153.136;
        location / {
                if ($http_user_agent ~ Trident) {
                        root /home/koushengrui/html;
                }
        }
}

以上配置表示若是發起請求的瀏覽器是IE或Edge瀏覽器的話,則首頁會是/home/koushengrui/html下的index.html文件,不然是/usr/local/nginx/html下的index.html文件。

注意,沒有else指令,沒有else指令,在if塊中不能使用index指令。

return指令:用於直接向客戶端返回響應狀態碼及重定向地址。return指令能夠在server塊、location塊、if塊中使用,用法爲:return code url。配置示例:

server {
    listen       80;
    server_name  192.168.153.136;

    location / {
        return 301 http://192.168.153.136:10000/image/example.png;
        root /home/koushengrui/html;
        index welcome.htm;
    }
}

若是請求地址是http://192.168.153.136/*** 的話,則此請求會被重定向至http://192.168.153.136:10000/image/example.png。

301是永久移動,302是臨時移動。

rewrite指令:經過正則表達式的使用來改變URI。這裏須要大量的正則表達式的知識,如今瞭解的還不透徹。包括域名跳轉、防盜鏈的功能都是用rewrite指令來作的。

四.反向代理與負載均衡

什麼是反向代理?

負載均衡

內置策略有3種,輪詢、加權輪詢、IP hash:

1.輪詢,顧名思義,就是服務器將每一個前端請求按順序(時間順序或者排列次序)逐一分配到不一樣的後端節點上,對於出現問題的後端節點自動去除;

2.加權輪詢,在基本的輪詢策略基礎上考慮各後端節點接受請求的權重,指定各後端節點被輪詢到的概率,主要用於後端節點性能不均的狀況下;

3.IP hash,是將前端的訪問IP進行hash操做,而後根據hash結果將請求分配給不一樣的後端節點。這樣會使得每一個前端訪問IP會固定訪問一個後端節點,好處是前端用戶的session只在一個後端節點上,沒必要考慮一個session存在多臺節點上而出現的session共享問題。

擴展策略有2種,url hash、fair:

4.url hash,將前端請求的url地址進行hash操做,根據hash結果將請求分配到不一樣的後端節點上;

5.fair,將前端請求轉發到負載最小的後端節點上。Nginx經過後端節點對請求的響應時間來判斷負載狀況,響應時間最短的節點負載就相對較輕,Nginx就會將前端請求轉發到此後端節點上。

五.gzib模塊

gzib on;#默認狀況下是off,要想啓動gzip功能,得設置爲on

gzip_min_length 1024;#當文件的長度大於1024字節時才壓縮,不然不壓縮,避免越壓越大

gzip_buffers 32 4k;#或者gzip_buffers 16 8k;設置gzip壓縮文件使用緩存空間的大小,第一個數是nginx服務器向系統申請緩存空間的個數,第二個數是每一個緩存空間的大小

gzip_comp_level 6;#設置gzip的壓縮程度,級別從1到9,1表示壓縮程度最低,效率最高,9表示壓縮程度最高,效率最低

gzip_types text/plain application/javascript text/css text/xml;#根據相應文件的MIME類型選擇性地開啓gzip壓縮功能,text/plain對應txt文件,application/javascript(或者text/javascript)對應js文件,text/css對應css文件,text/xml對應xml文件。這其中沒有寫html文件對應的MIME類型,是由於只要開啓了gzip功能,html文件、htm文件是默認壓縮的,寫的話會報錯。一般來講,只建議html/htm、css、js、xml文件進行壓縮,而圖片、音視頻文件不建議壓縮,由於壓縮效果很小。

六.expires緩存優化

通常對圖片進行expires配置

location ~* ^.+\.(png|jpg|jpeg|gif|ico|bmp|psd)$ {yyyy-MM-dd HH:mm:ss
       expires 1d;#y表示年,M表示月,d表示天,h表示小時,m表示分鐘,s表示秒
}

七.限速

location /download {
       if ($http_user_agent ~ Chrome){
                limit_rate_after 100M;
       }
       limit_rate         200k;
       root               /home/koushengrui;     
}

limit_rate_after表示多少大小以後纔開始限速,上例從100M開始限速,也就是說一個文件下載時前100M是不限速的,100M以後才限速

limit_rate表示限速多少,上例中限速200k/s

八.跨域

需添加以下配置:(參考連接 https://enable-cors.org/server_nginx.html,實測有效)

#
# Wide-open CORS config for nginx
#
location / {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
}

 

zeb系統生產上某一臺nginx服務器(有不少臺)配置以下:

user wls81 wls;
worker_processes  5;

error_log  /wls/apache/applogs/error.log;
pid        /wls/apache/applogs/nginx.pid;

events {
    use epoll;
    worker_connections  200000;
}

http {
#   include       mime.types;
    default_type  application/octet-stream;
    server_tokens off; # 不返回nginx版本號

    sendfile        on;
    keepalive_timeout  65;

    log_format access '$remote_addr - $remote_user [$time_local] "$request"' '$status $body_bytes_sent "$http_referer"' '"$http_user_agent" $http_x_forwarded_for';

    upstream ng_zeb {
        ip_hash;
        server 192.168.56.100:8080;
        server 192.168.56.101:8080;        server 192.168.56.102:8080;
        keepalive 32;
        check interval=3000 rise=2 fall=5 timeout=1000 type=tcp;
    }

    server {
        listen       0.0.0.0:31023;
        listen       0.0.0.0:31024 ssl;
        ssl_certificate       /wls/apache/ssl/xxx.crt;
        ssl_certificate_key   /wls/apache/ssl/xxx.key;

        access_log  /wls/apache/applogs/host.access.log access;
        rewrite ^/f5monweb(.*) /monitor_ng/$1;        location / {
            proxy_set_header Host $http_host;
            proxy_set_header Origin $http_origin;
            proxy_pass http://ng_zeb;
            index  index.html;
        }

        location /monitor_ng {
            root /wls/apache;
            index f5check.htm f5check.jsp;
        }

        location /nginx_status {
           stub_status on;
           access_log  off;
           allow 192.168.56.1;
           deny all;
        }
    }
} 
相關文章
相關標籤/搜索