Nginx系統學習篇(4)--linux環境配置

轉自:http://freeloda.blog.51cto.com/2033581/1285722

一、Nginx 配置文件說明

1.查看一下配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
[root@web ~]# cat /etc/nginx/nginx.conf
#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;   
    #    server_name  localhost;
    #    ssl                  on;  
    #    ssl_certificate      cert.pem;   
    #    ssl_certificate_key  cert.key;
    #    ssl_session_timeout  5m;
    #    ssl_protocols  SSLv2 SSLv3 TLSv1;  
    #    ssl_ciphers  HIGH:!aNULL:!MD5;   
    #    ssl_prefer_server_ciphers   on;
    #    location / {  
    #        root   html;   
    #        index  index.html index.htm;   
    #    }   
    #}
}

2.nginx 配置文件結構

Nginx配置文件主要分爲4部分:main(全局設置)、server(主機設置)、upstream(負載均衡服務器設置)和 location(URL匹配特定位置的設置)。main部分設置的指令將影響其他所有設置;server部分的指令主要用於指定主機和端口;upstream指令主要用於負載均衡,設置一系列的後端服務器;location部分用於匹配網頁位置。這四者之間的關係如下:server繼承main,location繼承server,upstream既不會繼承其他設置也不會被繼承。如下圖,

n3

在這4個部分當中,每個部分都包含若干指令,這些指令主要包含Nginx的主模塊指令、事件模塊指令、HTTP核心模塊指令。同時每個部分還可以使用其他HTTP模塊指令,例如Http SSL模塊、Http Gzip Static模塊和Http Addition模塊等。

下面通過一個Nginx配置實例,詳細介紹nginx.conf每個指令的含義。爲了能更清楚地瞭解Nginx的結構和每個配置選項的含義,這裏按照功能點將Nginx配置文件分爲7個部分依次講解。下面就圍繞這7個部分進行介紹。

3.配置文件詳解

(1).Nginx 的全局配置文件

1
2
3
4
5
6
7
8
9
10
11
#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;
worker_rlimit_nofile 65535; 
events {
    use epoll;
    worker_connections  1024;  
}

上面這段代碼中每個配置選項的含義解釋如下:

  • user是個主模塊指令,指定Nginx Worker進程運行用戶以及用戶組,默認由nobody賬號運行。

  • worker_processes是個主模塊指令,指定了Nginx要開啓的進程數。每個Nginx進程平均耗費10MB~12MB內存。根據經驗,一般指定一個進程足夠了,如果是多核CPU,建議指定和CPU的數量一樣多的進程數即可。(注,如果負載以CPU密集型應用爲主,如SSL或壓縮應用,則worker數應與CPU數相同;如果負載以IO密集型爲主,如響應大量內容給客戶端,則worker數應該爲CPU個數的1.5或2倍。)

  • error_log是個主模塊指令,用來定義全局錯誤日誌文件。日誌輸出級別有debug、info、notice、warn、error、crit可供選擇,其中,debug輸出日誌最爲最詳細,而crit輸出日誌最少。

  • pid是個主模塊指令,用來指定進程id的存儲文件位置。

  • worker_rlimit_nofile 用於綁定worker進程和CPU, Linux內核2.4以上可用。

  • events指令用來設定Nginx的工作模式及連接數上限。

  • use是個事件模塊指令,用來指定Nginx的工作模式。Nginx支持的工作模式有select、poll、kqueue、epoll、rtsig和/dev/poll。其中select和poll都是標準的工作模式,kqueue和epoll是高效的工作模式,不同的是epoll用在Linux平臺上,而kqueue用在BSD系統中。對於Linux系統,epoll工作模式是首選。

  • worker_connections也是個事件模塊指令,用於定義Nginx每個進程的最大連接數,默認是1024。最大客戶端連接數由worker_processes和worker_connections決定,即max_client=worker_processes*worker_connections,在作爲反向代理時變爲:max_clients = worker_processes * worker_connections/4。(注,進程的最大連接數受Linux系統進程的最大打開文件數限制,在執行操作系統命令“ulimit -n 65536”後worker_connections的設置才能生效。)

(2).HTTP服務器配置

注,接下來開始對HTTP服務器進行配置。下面這段內容是Nginx對HTTP服務器相關屬性的配置,代碼如下:

1
2
3
4
5
6
7
8
9
10
11
12
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;

下面詳細介紹這段代碼中每個配置選項的含義。

  • include是個主模塊指令,實現對配置文件所包含的文件的設定,可以減少主配置文件的複雜度。類似於Apache中的include方法。

  • default_type屬於HTTP核心模塊指令,這裏設定默認類型爲二進制流,也就是當文件類型未定義時使用這種方式,例如在沒有配置PHP環境時,Nginx是不予解析的,此時,用瀏覽器訪問PHP文件就會出現下載窗口。

  • log_format是Nginx的HttpLog模塊指令,用於指定Nginx日誌的輸出格式。main爲此日誌輸出格式的名稱,可以在下面的access_log指令中引用。

  • client_max_body_size用來設置允許客戶端請求的最大的單個文件字節數。

  • client_header_buffer_size用於指定來自客戶端請求頭的headerbuffer大小。對於大多數請求,1KB的緩衝區大小已經足夠,如果自定義了消息頭或有更大的cookie,可以增加緩衝區大小。這裏設置爲32KB。

  • large_client_header_buffers用來指定客戶端請求中較大的消息頭的緩存最大數量和大小, “4”爲個數,“128K”爲大小,最大緩存爲4個128KB。

  • sendfile參數用於開啓高效文件傳輸模式。將tcp_nopush和tcp_nodely兩個指令設置爲on,用於防止網絡阻塞。

  • keepalive_timeout用於設置客戶端連接保持活動的超時時間。在超過這個時間之後,服務器會關閉該連接。

  • client_header_timeout用於設置客戶端請求頭讀取超時時間。如果超過這個時間,客戶端還沒有發送任何數據,Nginx將返回“Request time out(408)”錯誤。

  • client_body_timeout用於設置客戶端請求主體讀取超時時間,默認值爲60。如果超過這個時間,客戶端還沒有發送任何數據,Nginx將返回“Request time out(408)”錯誤。

  • send_timeout用於指定響應客戶端的超時時間。這個超時僅限於兩個連接活動之間的時間,如果超過這個時間,客戶端沒有任何活動,Nginx將會關閉連接。

  • gzip用於設置開啓或者關閉gzip模塊,“gzip on”表示開啓gzip壓縮,實時壓縮輸出數據流。

(3).HttpGzip模塊配置

下面配置Nginx的HttpGzip模塊。這個模塊支持在線實時壓縮輸出數據流。要查看是否安裝了此模塊,需要使用下面的命令:

1
2
3
4
5
[root@web nginx-1.4.2]# nginx -V  
nginx version: nginx/1.4.2   
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC)   
TLS SNI support enabled   
configure arguments: --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

通過nginx -V 命令可以查看安裝Nginx時的編譯選項。由輸出可知,我們已經安裝了HttpGzip模塊。下面是HttpGzip模塊在Nginx配置中的相關屬性設置:

1
2
3
4
5
6
7
#gzip  on;
#gzip_min_length  1k;
#gzip_buffers     4  16k;
#gzip_http_version  1.1;
#gzip_comp_level  2;
#gzip_types  text/plain application/x-javascript text/css application/xml;
#gzip_vary  on;
  • gzip用於設置開啓或者關閉gzip模塊,“gzip on”表示開啓gzip壓縮,實時壓縮輸出數據流。

  • gzip_min_length用於設置允許壓縮的頁面最小字節數,頁面字節數從header頭的Content-Length中獲取。默認值是0,不管頁面多大都進行壓縮。建議設置成大於1K的字節數,小於1K可能會越壓越大。

  • gzip_buffers表示申請4個單位爲16K的內存作爲壓縮結果流緩存,默認值是申請與原始數據大小相同的內存空間來存儲gzip壓縮結果。

  • gzip_buffers表示申請4個單位爲16K的內存作爲壓縮結果流緩存,默認值是申請與原始數據大小相同的內存空間來存儲gzip壓縮結果。

  • gzip_comp_level用來指定gzip壓縮比,1 壓縮比最小,處理速度最快;9 壓縮比最大,傳輸速度快,但處理最慢,也比較消耗CPU資源。

  • gzip_types用來指定壓縮的類型,無論是否指定,“text/html”類型總是會被壓縮的。

  • gzip_vary選項可以讓前端的緩存服務器緩存經過gzip壓縮的頁面,例如,用Squid緩存經過Nginx壓縮的數據。

(4).負載均衡配置

下面設定負載均衡的服務器列表。

1
2
3
4
5
6
7
upstream test.net{
ip_hash;
server 192.168.10.13:80;
server 192.168.10.14:80  down;
server 192.168.10.15:8009  max_fails=3  fail_timeout=20s;
server 192.168.10.16:8080;
}
  • upstream是Nginx的HTTP Upstream模塊,這個模塊通過一個簡單的調度算法來實現客戶端IP到後端服務器的負載均衡。在上面的設定中,通過upstream指令指定了一個負載均衡器的名稱test.net。這個名稱可以任意指定,在後面需要用到的地方直接調用即可。

  • Nginx的負載均衡模塊目前支持4種調度算法,下面進行分別介紹,其中後兩項屬於第三方調度算法。      

  • 輪詢(默認)。每個請求按時間順序逐一分配到不同的後端服務器,如果後端某臺服務器宕機,故障系統被自動剔除,使用戶訪問不受影響。

  • Weight。指定輪詢權值,Weight值越大,分配到的訪問機率越高,主要用於後端每個服務器性能不均的情況下。

  • ip_hash。每個請求按訪問IP的hash結果分配,這樣來自同一個IP的訪客固定訪問一個後端服務器,有效解決了動態網頁存在的session共享問題。

  • fair。這是比上面兩個更加智能的負載均衡算法。此種算法可以依據頁面大小和加載時間長短智能地進行負載均衡,也就是根據後端服務器的響應時間來分配請求,響應時間短的優先分配。Nginx本身是不支持fair的,如果需要使用這種調度算法,必須下載Nginx的upstream_fair模塊。

  • url_hash。此方法按訪問url的hash結果來分配請求,使每個url定向到同一個後端服務器,可以進一步提高後端緩存服務器的效率。Nginx本身是不支持url_hash的,如果需要使用這種調度算法,必須安裝Nginx 的hash軟件包。

  • 在HTTP Upstream模塊中,可以通過server指令指定後端服務器的IP地址和端口,同時還可以設定每個後端服務器在負載均衡調度中的狀態。常用的狀態有:      

  • down,表示當前的server暫時不參與負載均衡。

  • backup,預留的備份機器。當其他所有的非backup機器出現故障或者忙的時候,纔會請求backup機器,因此這臺機器的壓力最輕。

  • max_fails,允許請求失敗的次數,默認爲1。當超過最大次數時,返回proxy_next_upstream 模塊定義的錯誤。

  • fail_timeout,在經歷了max_fails次失敗後,暫停服務的時間。max_fails可以和fail_timeout一起使用。

注意,當負載調度算法爲ip_hash時,後端服務器在負載均衡調度中的狀態不能是weight和backup。

(5).server虛擬主機配置

下面介紹對虛擬主機的配置。建議將對虛擬主機進行配置的內容寫進另外一個文件,然後通過include指令包含進來,這樣更便於維護和管理。

1
2
3
4
5
6
7
server{
listen         80;
server_name    192.168.12.188  www.test.net;
index index.html index.htm index.php;
root  /web/www/www.test.net
charset gb2312;
access_log  logs/www.test.net.access.log  main;
  • server標誌定義虛擬主機開始;

  • listen用於指定虛擬主機的服務器端口;

  • server_name用來指定IP地址或者域名,多個域名之間用空格分開;

  • index用於設定訪問的默認首頁地址;

  • root指令用於指定虛擬主機的網頁根目錄,這個目錄可以是相對路徑,也可以是絕對路徑;

  • charset用於設置網頁的默認編碼格式。

  • access_log用來指定此虛擬主機的訪問日誌存放路徑。最後的main用於指定訪問日誌的輸出格式。

(6).URL匹配配置

URL地址匹配是Nginx配置中最靈活的部分。 location支持正則表達式匹配,也支持條件判斷匹配,用戶可以通過location指令實現Nginx對動、靜態網頁的過濾處理。

格式:location [ = | ~ | ~* | ^~ ] uri { ... }

  • location URI {}:對當前路徑及子路徑下的所有對象都生效;

  • location = URI {}:精確匹配指定的路徑,不包括子路徑,因此,只對當前資源生效;

  • location ~ URI {},location ~* URI {}:模式匹配URI,此處的URI可使用正則表達式,~區分字符大小寫,~*不區分字符大小寫;

  • location ^~ URI {}:不使用正則表達式

案例1:

1
2
3
4
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$  {
                    root    /web/www/www.test.net;
                    expires 30d;
       }

說明:上面這段設置是通過location指令來對網頁URL進行分析處理,所有擴展名爲.gif、.jpg、.jpeg、.png、.bmp、.swf的靜態文件都交給Nginx處理,而expires用來指定靜態文件的過期時間,這裏是30天。

案例2:

1
2
3
4
location ~ ^/(upload|html)/  {
                root    /web/www/www.test.net;
                expires 30d;
}

說明:上面這段設置是將upload和html下的所有文件都交給Nginx來處理,當然,upload和html目錄包含/web/www/www.test.net目錄中。

案例3:

1
2
3
4
location ~ .*.jsp$ {
            index index.jsp;
            proxy_pass http://localhost:8080;
          }

說明:在最後這段設置中,location是對此虛擬主機下動態網頁的過濾處理,也就是將所有以.jsp爲後綴的文件都交給本機的8080端口處理。

location [ = | ~ | ~* | ^~ ] 優先級

  • location = URI {}:精確匹配指定的路徑,不包括子路徑,因此,只對當前資源生效;(優先級最高)

  • location ^~ URI {}:不使用正則表達式;(優先級次之)

  • location ~ URI {},location ~* URI {}:模式匹配URI,此處的URI可使用正則表達式,~區分字符大小寫,~*不區分字符大小寫;(優先級次之)

  • location URI {}:對當前路徑及子路徑下的所有對象都生效;(優先級最低)

案例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
location = / {  
    [ configuration A ]
}
location / {  
    [ configuration B ]
}
location /documents/ {
    [ configuration C ]
}
location ^~ /images/
{  
    [ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {  
    [ configuration E ]
}

說明:The “/” request will match configuration A, the “/index.html” request will match configuration B, the “/documents/document.html” request will match configuration C, the “/images/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E.

(7).StubStatus模塊配置

StubStatus模塊能夠獲取Nginx自上次啓動以來的工作狀態,此模塊非核心模塊,需要在Nginx編譯安裝時手工指定才能使用。以下指令指定啓用獲取Nginx工作狀態的功能。

1
2
3
4
5
6
location /NginxStatus {
    stub_status     on;
    access_log             logs/NginxStatus.log;
    auth_basic             "NginxStatus";
    auth_basic_user_file    ../htpasswd;
       }

  • stub_status爲“on”表示啓用StubStatus的工作狀態統計功能;

  • access_log 用來指定StubStatus模塊的訪問日誌文件;

  • auth_basic是Nginx的一種認證機制;

  • auth_basic_user_file用來指定認證的密碼文件。

由於Nginx的auth_basic認證採用的是與Apache兼容的密碼文件,因此需要用Apache的htpasswd命令來生成密碼文件。例如要添加一個webadmin用戶,可以使用下面的方式生成密碼文件:

1
/usr/local/apache/bin/htpasswd -c  /opt/nginx/conf/htpasswd webadmin

要查看Nginx的運行狀態,可以輸入http://ip/ NginxStatus,然後輸入剛剛創建的用戶名和密碼就可以看到如下信息:

1
2
3
4
Active connections: 1
server accepts handled requests
393411 393411 393799
Reading: 0 Writing: 1 Waiting: 0
  • Active connections表示當前活躍的連接數。

  • 第三行的3個數字表示 Nginx當前總共處理了393411個連接, 成功創建了393 411次握手,總共處理了393 799個請求。

  • 最後一行的Reading表示Nginx讀取到客戶端Header信息數; Writing表示Nginx返回給客戶端的Header信息數;Waiting表示Nginx已經處理完、正在等候下一次請求指令時的駐留連接數。

補充說明:

1
2
3
4
5
error_page  404              /404.html;
error_page   500 502 503 504  /50x.html;
location = /50x.html {
           root   html;
       }

在最後這段設置中,設置了虛擬主機的錯誤信息返回頁面,通過error_page指令可以定製各種錯誤信息的返回頁面。在默認情況下,Nginx會在主目錄的html目錄中查找指定的返回頁面。特別需要注意的是,這些錯誤信息的返回頁面大小一定要超過512KB,否則會被IE瀏覽器替換爲IE默認的錯誤頁面。好了,到這裏nginx的配置文件講解全部完成。下面我們來說一說nginx命令參數。

二、Nginx 命令參數

不像許多其他軟件系統,Nginx 僅有數個命令行參數,完全通過配置文件來配置(想象一下)。

  • [#options 選項]

  • [#example 示例]

  • [#lncus 使用信號加載新的配置]

  • [#utnbotf 平滑升級到新的二進制代碼]

選項

  • -c </path/to/config> 爲 Nginx 指定一個配置文件,來代替缺省的。

  • -t 不運行,而僅僅測試配置文件。nginx 將檢查配置文件的語法的正確性,並嘗試打開配置文件中所引用到的文件。

  • -v 顯示 nginx 的版本。

  • -V 顯示 nginx 的版本,編譯器版本和配置參數。

更多

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@web ~]# nginx -h 
nginx version: nginx/1.4.2 
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options: 
  -?,-h         : this help 
  -v            : show version and exit 
  -V            : show version and configure options then exit 
  -t            : test configuration and exit 
  -q            : suppress non-error messages during configuration testing 
  -s signal     : send signal to a master process: stop, quit, reopen, reload 
  -p prefix     : set prefix path (default: /usr/
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf) 
  -g directives : set global directives out of configuration file

三、配置Nginx提供Web服務

1.提供測頁面

1
2
3
4
5
6
7
8
[root@web nginx]# mkdir -pv /data/www 
mkdir: 已創建目錄 "/data/www" 
[root@web nginx]# cd /data/www 
[root@web www]# ll 
總用量 0
[root@web www]# cat index.html
<h1>www.nginx.org</h1>
[root@web www]# chown -R nginx.nginx /data/www/*

2.備份配置文件

1
2
3
4
5
6
[root@web ~]# cd /etc/nginx/ 
[root@web nginx]# cp nginx.conf nginx.conf.bak 
[root@web nginx]# ls 
fastcgi.conf          fastcgi_params.default  mime.types          nginx.conf.bak      scgi_params.default   win-utf 
fastcgi.conf.default  koi-utf                 mime.types.default  nginx.conf.default  uwsgi_params 
fastcgi_params        koi-win                 nginx.conf          scgi_params         uwsgi_params.default

3.修改配置文件

1
2
3
4
5
6
7
8
9
10
[root@web www]# vim /etc/nginx/nginx.conf
server { 
      listen       80; 
      server_name  localhost;
      #charset koi8-r;
      #access_log  logs/host.access.log  main;
      location / { 
          root   /data/www
          index  index.html index.htm; 
      }

4.重新加載nginx配置

1
2
3
4
[root@web run]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
重新載入 nginx:                                           [確定]

5.測試一下

n4

好了,一個基本的web服務器已配置完成,簡單吧。

四、配置Nginx的虛擬主機

1.修改配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@web www]# vim /etc/nginx/nginx.conf
server { 
        listen       80; 
        server_name  www.nginx.com; 
        location / { 
            root   /data/www
            index  index.html index.htm; 
        
    }
    server { 
        listen       80; 
        server_name  www.test.com; 
        location / { 
            root   /data/test
            index  index.html index.htm; 
        
    }

2.提供測試頁面

1
2
3
4
[root@web data]# mkdir test 
[root@web data]# cd test/ 
[root@web test]# cat index.html 
<h1>www.test.com</h1>

3.重新加載nginx配置

1
2
3
4
[root@web run]# service nginx reload 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 
nginx: configuration file /etc/nginx/nginx.conf test is successful 
重新載入 nginx:                                           [確定]

4.修改測試機的hosts文件

1
2
3
4
Windows 7下路徑:C:\Windows\System32\drivers\etc\hosts
增加兩行:
192.168.18.201    www.nginx.com 
192.168.18.201    www.test.com

5.測試一下

n5

n6

好了,到這裏基於域名的虛擬主機配置完成。

五、配置Nginx的訪問控制

基於用戶的訪問控制,

1.提供測試文件

1
2
3
4
5
6
7
8
9
[root@web run]# cd /data/www/ 
[root@web www]# ll 
總用量 4 
-rw-r--r-- 1 nginx nginx 23 8月  29 20:04 index.html 
[root@web www]# mkdir bbs 
[root@web www]# cd bbs/ 
[root@web bbs]# vim index.html 
[root@web bbs]# cat index.html 
<h1>Auth Page</h1>

2.修改配置文件

1
2
3
4
5
6
location /data 
           root /www/bbs
           index index.html 
           auth_basic             "Auth Page";
           auth_basic_user_file  /etc/nginx/.user; 
       }

3.安裝httpd

1
[root@web bbs]# yum install -y httpd

4.生成認證文件

1
2
3
4
5
6
7
8
9
[root@web bbs]# htpasswd -c -m /etc/nginx/.user nginx 
New password: 
Re-type new password: 
Adding password for user nginx 
[root@web bbs]# ls -a /etc/nginx/ 
.                     fastcgi_params          mime.types          nginx.conf.default   .user 
..                    fastcgi_params.default  mime.types.default  .nginx.conf.swp      uwsgi_params 
fastcgi.conf          koi-utf                 nginx.conf          scgi_params          uwsgi_params.default 
fastcgi.conf.default  koi-win                 nginx.conf.bak      scgi_params.default  win-utf

5.重新加載一下nginx配置文件

1
2
3
4
[root@web bbs]# service nginx reload 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 
nginx: configuration file /etc/nginx/nginx.conf test is successful 
重新載入 nginx:                                           [確定]

6.測試一下

(1).輸入用戶名nginx,密碼123456

n7

(2).顯示頁面

n8

基於IP的訪問控制,

1.控制指令

  • allow 定義允許訪問的規則

  • deny 定義拒絕訪問的規則

  • allow all或deny all 定義默認規則

2.案例

1
2
3
4
5
6
7
8
9
10
[root@web test]# vim /etc/nginx/nginx.conf
location / { 
         root   /data/www
         index  index.html index.htm; 
         #auth_basic "Auth Page";           
         #auth_basic_user_file /etc/nginx/.user; 
         deny 192.168.18.138; 
         allow 192.168.18.0/24;
         deny  all; 
     }

n9

注,大家可以看到不允許訪問。allow與deny指令使用很簡單,唯一與httpd不同的是nginx沒有定義默認規則,所以默認規則得自己定義。我這裏定義是dell all;默認拒絕所有。

六、配置Nginx提供狀態頁面

1.修改配置文件

1
2
3
4
5
6
7
[root@web test]# vim /etc/nginx/nginx.conf
location /status 
     root /; 
     stub_status on; 
     auth_basic "NginxStatus";              
     auth_basic_user_file /etc/nginx/.user; 
     }

2.重新加載一下配置文件

3.測試

n10

n11

九、配置Nginx的錯誤頁面

1.提供404錯誤頁面

1
2
3
4
5
6
7
8
9
10
11
[root@web www]# ll 
總用量 8 
drwxr-xr-x 2 root  root  4096 8月  29 20:36 bbs 
-rw-r--r-- 1 nginx nginx   23 8月  29 20:04 index.html 
[root@web www]# vim 404.html 
[root@web www]# cat 404.html 
<h1>404 error</h1>
<h1>404 error</h1>
<h1>404 error</h1>
<h1>404 error</h1>
……

2.修改配置文件

1
2
3
4
[root@web test]# vim /etc/nginx/nginx.conf
server {
error_page  404                 /404.html;
}

3.重新加載一下nginx配置文件

1
2
3
4
[root@web www]# service nginx reload 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 
nginx: configuration file /etc/nginx/nginx.conf test is successful 
重新載入 nginx:                                           [確定]

4.我們訪問一下不存在的頁面

n12

七、配置Nginx打開目錄瀏覽功能

1.指令說明

Nginx默認是不允許列出整個目錄的。如需此功能,打開nginx.conf文件,在location server 或 http段中加入autoindex on;另外兩個參數最好也加上去,

  • autoindex_exact_size off;默認爲on,顯示出文件的確切大小,單位是bytes。改爲off後,顯示出文件的大概大小,單位是kB或者MB或者GB。

  • autoindex_localtime on;默認爲off,顯示的文件時間爲GMT時間。改爲on後,顯示的文件時間爲文件的服務器時間。

2.修改配置文件

1
2
3
4
5
6
7
8
9
10
11
server { 
    listen       80; 
    server_name  www.nginx.com; 
    location / { 
    autoindex on; 
    autoindex_exact_size on; 
    autoindex_localtime on; 
    root   /data/www
    index  123.html; 
    
}

3.重新加載配置文件

1
2
3
4
[root@web www]# service nginx reload 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 
nginx: configuration file /etc/nginx/nginx.conf test is successful 
重新載入 nginx:                                           [確定]

4.測試一下

n13

八、配置Nginx基於ssl提供https服務

1.創建CA自簽證書

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
[root@web ~]# cd /etc/pki/CA/ 
[root@web CA]# ls 
certs  crl  newcerts  private 
[root@web CA]# cd private/ 
[root@web private]# ls 
[root@web private]# (umask 077; openssl genrsa 2048 > cakey.pem) #生成私鑰 
Generating RSA private key, 2048 bit long modulus 
...............................+++ 
.............+++ 
e is 65537 (0x10001) 
[root@web CA]# openssl req -new -x509 -key ./private/cakey.pem -out cacert.pem #生成自簽證書 
You are about to be asked to enter information that will be incorporated 
into your certificate request. 
What you are about to enter is what is called a Distinguished Name or a DN. 
There are quite a few fields but you can leave some blank 
For some fields there will be a default value, 
If you enter '.', the field will be left blank. 
----- 
Country Name (2 letter code) [XX]:CN 
State or Province Name (full name) []:SH 
Locality Name (eg, city) [Default City]:XH  
Organization Name (eg, company) [Default Company Ltd]:JJHH    
Organizational Unit Name (eg, section) []:Tech 
Common Name (eg, your name or your server's hostname) []:ca.test.com 
Email Address []:caadmin@test.com 
[root@web private]# ll 
總用量 8 
-rw------- 1 root root 1679 8月  29 23:31 cakey.pem 
[root@web CA]# touch serial 
[root@web CA]# echo 01 > serial 
[root@web CA]# touch index.txt
[root@web CA]# ll 
總用量 24 
-rw-r--r--  1 root root 1375 8月  29 23:34 cacert.pem 
drwxr-xr-x. 2 root root 4096 3月   5 06:22 certs 
drwxr-xr-x. 2 root root 4096 3月   5 06:22 crl 
-rw-r--r--  1 root root    0 8月  29 23:35 index.txt 
drwxr-xr-x. 2 root root 4096 3月   5 06:22 newcerts 
drwx------. 2 root root 4096 8月  29 23:49 private 
-rw-r--r--  1 root root    3 8月  29 23:35 serial

2.生成證書申請

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@web ~]# mkdir /etc/nginx/ssl 
[root@web CA]# cd /etc/nginx/ssl/
[root@web ssl]# (umask 077; openssl genrsa 1024 > nginx.key) #生成私鑰 
Generating RSA private key, 1024 bit long modulus 
.........................................++++++ 
..................................++++++ 
e is 65537 (0x10001)
[root@web ssl]# openssl req -new -key nginx.key -out nginx.csr 
You are about to be asked to enter information that will be incorporated 
into your certificate request. 
What you are about to enter is what is called a Distinguished Name or a DN. 
There are quite a few fields but you can leave some blank 
For some fields there will be a default value, 
If you enter '.', the field will be left blank. 
----- 
Country Name (2 letter code) [XX]:CN 
State or Province Name (full name) []:SH 
Locality Name (eg, city) [Default City]:XH 
Organization Name (eg, company) [Default Company Ltd]:JJHH 
Organizational Unit Name (eg, section) []:Tech 
Common Name (eg, your name or your server's hostname) []:www.test.com 
Email Address []:
Please enter the following 'extra' attributes 
to be sent with your certificate request 
A challenge password []: 
An optional company name []:

3. 讓CA簽名並頒發證書

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[root@web ssl]# openssl ca -in nginx.csr -out nginx.crt -days 3650 
Using configuration from /etc/pki/tls/openssl.cnf 
Check that the request matches the signature 
Signature ok 
Certificate Details: 
        Serial Number: 1 (0x1) 
        Validity 
            Not Before: Aug 29 15:51:53 2013 GMT 
            Not After : Aug 27 15:51:53 2023 GMT 
        Subject: 
            countryName               = CN 
            stateOrProvinceName       = SH 
            organizationName          = JJHH 
            organizationalUnitName    = Tech 
            commonName                = www.test.com 
        X509v3 extensions: 
            X509v3 Basic Constraints: 
                CA:FALSE 
            Netscape Comment: 
                OpenSSL Generated Certificate 
            X509v3 Subject Key Identifier: 
                60:87:97:14:D5:A2:23:B9:C5:13:97:5D:0D:B9:D7:C3:C2:66:F0:4B 
            X509v3 Authority Key Identifier: 
                keyid:9E:3E:5B:84:06:BE:68:01:C9:16:7C:08:5F:C5:54:0D:7B:FC:FA:87
Certificate is to be certified until Aug 27 15:51:53 2023 GMT (3650 days) 
Sign the certificate? [y/n]:y
1 out of 1 certificate requests certified, commit? [y/n]y 
Write out database with 1 new entries 
Data Base Updated

4.修改配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
server { 
      listen       443; 
      server_name  localhost;
      ssl                  on; 
      ssl_certificate      /etc/nginx/ssl/nginx.crt; 
      ssl_certificate_key  /etc/nginx/ssl/nginx.key;
      ssl_session_timeout  5m;
      ssl_protocols  SSLv2 SSLv3 TLSv1; 
      ssl_ciphers  HIGH:!aNULL:!MD5; 
      ssl_prefer_server_ciphers   on;
      location / { 
          root   html; 
          index  index.html index.htm; 
      
  }

5.重新啓動一下nginx服務器

1
2
3
4
5
[root@web ssl]# service nginx restart 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok 
nginx: configuration file /etc/nginx/nginx.conf test is successful 
停止 nginx:                                               [確定] 
正在啓動 nginx:                                           [確定]

6.查看一下端口   

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@web ssl]# netstat -ntlp 
Active Internet connections (only servers) 
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name 
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      10661/nginx       
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1033/sshd         
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1110/master       
tcp        0      0 127.0.0.1:6010              0.0.0.0:*                   LISTEN      9599/sshd         
tcp        0      0 0.0.0.0:443                 0.0.0.0:*                   LISTEN      10661/nginx       
tcp        0      0 127.0.0.1:6012              0.0.0.0:*                   LISTEN      9470/sshd         
tcp        0      0 :::22                       :::*                        LISTEN      1033/sshd         
tcp        0      0 ::1:25                      :::*                        LISTEN      1110/master       
tcp        0      0 ::1:6010                    :::*                        LISTEN      9599/sshd         
tcp        0      0 ::1:6012                    :::*                        LISTEN      9470/sshd

7.測試一下

n14

n15

好了,nginx作爲Web服務器的基本配置全部演示完成


發佈了50 篇原創文章 · 獲贊 424 · 訪問量 40萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章