nginx 服務和基本配置

一、序言

Nginx是lgor Sysoev爲俄羅斯訪問量第二的rambler.ru站點設計開發的。從2004年發佈至今,憑藉開源的力量,已經接近成熟與完善。

Nginx功能豐富,可作爲HTTP服務器,也可作爲反向代理服務器,郵件服務器。支持FastCGI、SSL、Virtual Host、URL Rewrite、Gzip等功能。並且支持很多第三方的模塊擴展。

Nginx的穩定性、功能集、示例配置文件和低系統資源的消耗讓他後來居上,在全球活躍的網站中有12.18%的使用比率,大約爲2220萬個網站。

牛逼吹的差不多啦,如果你還不過癮,你可以百度百科或者一些書上找到這樣的誇耀,比比皆是。

 

二、Nginx常用功能

1、Http代理,反向代理:作爲web服務器最常用的功能之一,尤其是反向代理。

這裏我給來2張圖,對正向代理與反響代理做個詮釋,具體細節,大家可以翻閱下資料。

Nginx在做反向代理時,提供性能穩定,並且能夠提供配置靈活的轉發功能。Nginx可以根據不同的正則匹配,採取不同的轉發策略,比如圖片文件結尾的走文件服務器,動態頁面走web服務器,只要你正則寫的沒問題,又有相對應的服務器解決方案,你就可以隨心所欲的玩。並且Nginx對返回結果進行錯誤頁跳轉,異常判斷等。如果被分發的服務器存在異常,他可以將請求重新轉發給另外一臺服務器,然後自動去除異常服務器。

2、負載均衡

Nginx提供的負載均衡策略有2種:內置策略和擴展策略。內置策略爲輪詢,加權輪詢,Ip hash。擴展策略,就天馬行空,只有你想不到的沒有他做不到的啦,你可以參照所有的負載均衡算法,給他一一找出來做下實現。

上3個圖,理解這三種負載均衡算法的實現

Ip hash算法,對客戶端請求的ip進行hash操作,然後根據hash結果將同一個客戶端ip的請求分發給同一臺服務器進行處理,可以解決session不共享的問題。 

3、web緩存

Nginx可以對不同的文件做不同的緩存處理,配置靈活,並且支持FastCGI_Cache,主要用於對FastCGI的動態程序進行緩存。配合着第三方的ngx_cache_purge,對制定的URL緩存內容可以的進行增刪管理。

4、Nginx相關地址

源碼:https://trac.nginx.org/nginx/browser

官網:http://www.nginx.org/

 

三、Nginx配置文件結構

如果你下載好啦,你的安裝文件,不妨打開conf文件夾的nginx.conf文件,Nginx服務器的基礎配置,默認的配置也存放在此。

在nginx.conf的註釋符號位#

nginx文件的結構,這個對剛入門的同學,可以多看兩眼。

默認的config 

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   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;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

nginx文件結構

...              #全局塊

events {         #events塊
   ...
}

http      #http塊
{
    ...   #http全局塊
    server        #server塊
    { 
        ...       #server全局塊
        location [PATTERN]   #location塊
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局塊
}

1、全局塊:配置影響nginx全局的指令。一般有運行nginx服務器的用戶組,nginx進程pid存放路徑,日誌存放路徑,配置文件引入,允許生成worker process數等。

2、events塊:配置影響nginx服務器或與用戶的網絡連接。有每個進程的最大連接數,選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啓多個網絡連接序列化等。

3、http塊:可以嵌套多個server,配置代理,緩存,日誌定義等絕大多數功能和第三方模塊的配置。如文件引入,mime-type定義,日誌自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。

4、server塊:配置虛擬主機的相關參數,一個http中可以有多個server。

5、location塊:配置請求的路由,以及各種頁面的處理情況。

下面給大家上一個配置文件,作爲理解,同時也配入我搭建的一臺測試機中,給大家示例。 

########### 每個指令必須有分號結束。#################
#user administrator administrators;  #配置用戶或者組,默認爲nobody nobody。
#worker_processes 2;  #允許生成的進程數,默認爲1
#pid /nginx/pid/nginx.pid;   #指定nginx進程運行文件存放地址
error_log log/error.log debug;  #制定日誌路徑,級別。這個設置可以放入全局塊,http塊,server塊,級別以此爲:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #設置網路連接序列化,防止驚羣現象發生,默認爲on
    multi_accept on;  #設置一個進程是否同時接受多個網絡連接,默認爲off
    #use epoll;      #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大連接數,默認爲512
}
http {
    include       mime.types;   #文件擴展名與文件類型映射表
    default_type  application/octet-stream; #默認文件類型,默認爲text/plain
    #access_log off; #取消服務日誌    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定義格式
    access_log log/access.log myFormat;  #combined爲日誌格式的默認值
    sendfile on;   #允許sendfile方式傳輸文件,默認爲off,可以在http塊,server塊,location塊。
    sendfile_max_chunk 100k;  #每個進程每次調用傳輸數量不能大於設定的值,默認爲0,即不設上限。
    keepalive_timeout 65;  #連接超時時間,默認爲75s,可以在http,server,location塊。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #熱備
    }
    error_page 404 https://www.baidu.com; #錯誤頁
    server {
        keepalive_requests 120; #單連接請求上限次數。
        listen       4545;   #監聽端口
        server_name  127.0.0.1;   #監聽地址       
        location  ~*^.+$ {       #請求的url過濾,正則匹配,~爲區分大小寫,~*爲不區分大小寫。
           #root path;  #根目錄
           #index vv.txt;  #設置默認頁
           proxy_pass  http://mysvr;  #請求轉向mysvr 定義的服務器列表
           deny 127.0.0.1;  #拒絕的ip
           allow 172.18.5.54; #允許的ip           
        } 
    }
}

上面是nginx的基本配置,需要注意的有以下幾點:

1.$remote_addr 與$http_x_forwarded_for 用以記錄客戶端的ip地址; 

2.$remote_user :用來記錄客戶端用戶名稱;

3.$time_local : 用來記錄訪問時間與時區;

4.$request : 用來記錄請求的url與http協議;

5.$status : 用來記錄請求狀態;成功是200, 

6.$body_bytes_s ent :記錄發送給客戶端文件主體內容大小;

7.$http_referer :用來記錄從那個頁面鏈接訪問過來的;

8.$http_user_agent :記錄客戶端瀏覽器的相關信息;

9、驚羣現象:一個網路連接到來,多個睡眠的進程被同事叫醒,但只有一個進程能獲得鏈接,這樣會影響系統性能。

10、每個指令必須有分號結束。

官網對各個模塊參數配置的解釋說明網址: Nginx中文文檔

##代碼塊中的events、http、server、location、upstream等都是塊配置項##
##塊配置項可以嵌套。內層塊直接繼承外層快,例如:server塊裏的任意配置都是基於http塊裏的已有配置的##
 
##Nginx worker進程運行的用戶及用戶組 
#語法:user username[groupname]    默認:user nobody nobody
#user用於設置master進程啓動後,fork出的worker進程運行在那個用戶和用戶組下。當按照"user username;"設置時,用戶組名與用戶名相同。
#若用戶在configure命令執行時,使用了參數--user=usergroup 和 --group=groupname,此時nginx.conf將使用參數中指定的用戶和用戶組。
#user  nobody;
 
##Nginx worker進程個數:其數量直接影響性能。
#每個worker進程都是單線程的進程,他們會調用各個模塊以實現多種多樣的功能。如果這些模塊不會出現阻塞式的調用,那麼,有多少CPU內核就應該配置多少個進程,反之,有可能出現阻塞式調用,那麼,需要配置稍多一些的worker進程。
worker_processes  1;
 
##ssl硬件加速。
#用戶可以用OpneSSL提供的命令來查看是否有ssl硬件加速設備:openssl engine -t
#ssl_engine device;
 
##守護進程(daemon)。是脫離終端在後臺允許的進程。它脫離終端是爲了避免進程執行過程中的信息在任何終端上顯示。這樣一來,進程也不會被任何終端所產生的信息所打斷。##
##關閉守護進程的模式,之所以提供這種模式,是爲了放便跟蹤調試nginx,畢竟用gdb調試進程時最繁瑣的就是如何繼續跟進fork出的子進程了。##
##如果用off關閉了master_proccess方式,就不會fork出worker子進程來處理請求,而是用master進程自身來處理請求
#daemon off;   #查看是否以守護進程的方式運行Nginx 默認是on 
#master_process off; #是否以master/worker方式工作 默認是on
 
##error日誌的設置#
#語法: error_log /path/file level;
#默認: error_log / log/error.log error;
#當path/file 的值爲 /dev/null時,這樣就不會輸出任何日誌了,這也是關閉error日誌的唯一手段;
#leve的取值範圍是debug、info、notice、warn、error、crit、alert、emerg從左至右級別依次增大。
#當level的級別爲error時,error、crit、alert、emerg級別的日誌就都會輸出。大於等於該級別會輸出,小於該級別的不會輸出。
#如果設定的日誌級別是debug,則會輸出所有的日誌,這一數據量會很大,需要預先確保/path/file所在的磁盤有足夠的磁盤空間。級別設定到debug,必須在configure時加入 --with-debug配置項。
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
##pid文件(master進程ID的pid文件存放路徑)的路徑
#pid        logs/nginx.pid;
 
 
events {
 #僅對指定的客戶端輸出debug級別的日誌: 語法:debug_connection[IP|CIDR]
 #這個設置項實際上屬於事件類配置,因此必須放在events{……}中才會生效。它的值可以是IP地址或者是CIRD地址。
 	#debug_connection 10.224.66.14;  #或是debug_connection 10.224.57.0/24
 #這樣,僅僅以上IP地址的請求才會輸出debug級別的日誌,其他請求仍然沿用error_log中配置的日誌級別。
 #注意:在使用debug_connection前,需確保在執行configure時已經加入了--with-debug參數,否則不會生效。
	worker_connections  1024;
}
 
##核心轉儲(coredump):在Linux系統中,當進程發生錯誤或收到信號而終止時,系統會將進程執行時的內存內容(核心映像)寫入一個文件(core文件),以作爲調試只用,這就是所謂的核心轉儲(coredump).
 
http {
##嵌入其他配置文件 語法:include /path/file
#參數既可以是絕對路徑也可以是相對路徑(相對於Nginx的配置目錄,即nginx.conf所在的目錄)
    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  logs/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
 
    #gzip  on;
 
    server {
##listen監聽的端口
#語法:listen address:port [ default(deprecated in 0.8.21) | default_server | [ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ssl ] ]
#default_server: 如果沒有設置這個參數,那麼將會以在nginx.conf中找到的第一個server塊作爲默認server塊
	listen       8080;
 
#主機名稱:其後可以跟多個主機名稱,開始處理一個HTTP請求時,nginx會取出header頭中的Host,與每個server中的server_name進行匹配,以此決定到底由那一個server來處理這個請求。有可能一個Host與多個server塊中的server_name都匹配,這時會根據匹配優先級來選擇實際處理的server塊。server_name與Host的匹配優先級見文末。
	 server_name  localhost;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        #location / {
        #    root   html;
        #    index  index.html index.htm;
        #}
 
##location 語法: location [=|~|~*|^~] /uri/ { ... }
# location的使用實例見文末。
#注意:location時有順序的,當一個請求有可能匹配多個location時,實際上這個請求會被第一個location處理。
	location / {
	proxy_pass http://192.168.1.60;
        }
 
        #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;
        }
 
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
 
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
 
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
 
 
 
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
 
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
 
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
 
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
 
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
}

 

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