Nginx安裝學習使用詳細記錄

dbasdk發表於2014-07-21
前言:
選擇Nginx的優點:
Nginx 可以在大多數 Unix like OS 上編譯執行,並有 Windows 移植版。 Nginx 的1.4.0穩定版已經於2013年4月24日釋出,一般情況下,對於新建站點,建議使用最新穩定版作為生產版本,已有站點的升級急迫性不高。Nginx 的原始碼使用 2-clause BSD-like license。
Nginx 是一個很強大的高效能Web和反向代理伺服器,它具有很多非常優越的特性:
在高連線併發的情況下,Nginx是Apache伺服器不錯的替代品:Nginx在美國是做虛擬主機生意的老闆們經常選擇的軟體平臺之一。能夠支援高達 50,000 個併發連線數的響應,感謝Nginx為我們選擇了 epoll and kqueue作為開發模型。

1.1 執行安裝
  1. tar -xvf nginx-1.4.2.tar.gz
  2. cd nginx-1.4.2
  3. ./configure --prefix=/usr/nginx --with-http_stub_status_module --with-debug --with-http_realip_module --with-http_ssl_module


  4. [root@localhost nginx-1.4.2]# make install
  5. ......
  6. test -d \'/usr/nginx/logs\' || mkdir -p \'/usr/nginx/logs\'
  7. test -d \'/usr/nginx/logs\' || mkdir -p \'/usr/nginx/logs\'
  8. test -d \'/usr/nginx/html\' || cp -R html \'/usr/nginx\'
  9. test -d \'/usr/nginx/logs\' || mkdir -p \'/usr/nginx/logs\'

1.2 檢視程式數
程式數是與top出來的cpu數量是一樣的。在/usr/local/nginx/conf/nginx.conf配置檔案裡面的worker_processes引數。
worker_processes指明瞭nginx要開啟的程式數,據官方說法,一般開一個就夠了,多開幾個,可以減少機器io帶來的影響。據實踐表明,nginx的這個引數在一般情況下開4個或8個就可以了,再往上開的話最佳化不太大。據另一種說法是,nginx開啟太多的程式,會影響主程式排程,所以佔用的cpu會增高。
  1. [root@lb-net-2 ~]# ps -eaf|grep nginx
  2. root 2221 1382 0 18:06 pts/0 00:00:00 grep nginx
  3. root 16260 1 0 Jun18 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
  4. nobody 16261 16260 0 Jun18 ? 00:01:26 nginx: worker process
  5. nobody 16262 16260 0 Jun18 ? 00:01:32 nginx: worker process
  6. nobody 16263 16260 0 Jun18 ? 00:01:25 nginx: worker process
  7. nobody 16264 16260 0 Jun18 ? 00:01:33 nginx: worker process
  8. nobody 16265 16260 0 Jun18 ? 00:01:32 nginx: worker process
  9. nobody 16266 16260 0 Jun18 ? 00:01:24 nginx: worker process
  10. nobody 16267 16260 0 Jun18 ? 00:01:32 nginx: worker process
  11. nobody 16268 16260 0 Jun18 ? 00:01:23 nginx: worker process
  12. nobody 16269 16260 0 Jun18 ? 00:01:32 nginx: worker process
  13. nobody 16270 16260 0 Jun18 ? 00:01:26 nginx: worker process
  14. nobody 16271 16260 0 Jun18 ? 00:01:32 nginx: worker process
  15. nobody 16272 16260 0 Jun18 ? 00:01:25 nginx: worker process
  16. nobody 16273 16260 0 Jun18 ? 00:01:26 nginx: worker process
  17. nobody 16274 16260 0 Jun18 ? 00:01:32 nginx: worker process
  18. nobody 16275 16260 0 Jun18 ? 00:01:32 nginx: worker process
  19. nobody 16276 16260 0 Jun18 ? 00:01:33 nginx: worker process
  20. nobody 16277 16260 0 Jun18 ? 00:01:24 nginx: worker process
  21. nobody 16278 16260 0 Jun18 ? 00:01:24 nginx: worker process
  22. nobody 16279 16260 0 Jun18 ? 00:01:30 nginx: worker process
  23. nobody 16280 16260 0 Jun18 ? 00:01:24 nginx: worker process
  24. nobody 16281 16260 0 Jun18 ? 00:01:32 nginx: worker process
  25. nobody 16282 16260 0 Jun18 ? 00:01:32 nginx: worker process
  26. nobody 16283 16260 0 Jun18 ? 00:01:25 nginx: worker process
  27. nobody 16284 16260 0 Jun18 ? 00:01:26 nginx: worker process

2 配置檔案
2.1 Nginx反向代理實踐
省過

2.2 Nginx Rewrite重新定向
使用nginx做重新定向。
nginx參考網址:http://blog.sina.com.cn/s/blog_97688f8e0100zws5.html
語法規則: location [=|~|~*|^~] /uri/ { … }
= 開頭表示精確匹配
^~ 開頭表示uri以某個常規字串開頭,理解為匹配 url路徑即可。nginx不對url做編碼,因此請求為/static/20%/aa,可以被規則^~ /static/ /aa匹配到(注意是空格)。
~ 開頭表示區分大小寫的正則匹配
~*  開頭表示不區分大小寫的正則匹配
!~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配 的正則
/ 通用匹配,任何請求都會匹配到。
多個location配置的情況下匹配順序為(參考資料而來,還未實際驗證,試試就知道了,不必拘泥,僅供參考):
首先匹配 =,其次匹配^~, 其次是按檔案中順序的正則匹配,最後是交給 / 通用匹配。當有匹配成功時候,停止匹配,按當前匹配規則處理請求。
例子,有如下匹配規則:
location = / {
   #規則A
}
location = /login {
   #規則B
}
location ^~ /static/ {
   #規則C
}
location ~ \.(gif|jpg|png|js|css)$ {
   #規則D
}
location ~* \.png$ {
   #規則E
}
location !~ \.xhtml$ {
   #規則F
}
location !~* \.xhtml$ {
   #規則G
}
location / {
   #規則H
}
那麼產生的效果如下:
訪問根目錄/, 比如 將匹配規則A
訪問 login 將匹配規則B,register 則匹配規則H
訪問 static/a.html 將匹配規則C
訪問 a.gif, b.jpg 將匹配規則D和規則E,但是規則D順序優先,規則E不起作用,而 static/c.png 則優先匹配到規則C
訪問 a.PNG 則匹配規則E,而不會匹配規則D,因為規則E不區分大小寫。
訪問 a.xhtml 不會匹配規則F和規則G,a.XHTML不會匹配規則G,因為不區分大小寫。規則F,規則G屬於排除法,符合匹配規則但是不會匹配到,所以想想看實際應用中哪裡會用到。
訪問 category/id/1111 則最終匹配到規則H,因為以上規則都不匹配,這個時候應該是nginx轉發請求給後端應用伺服器,比如FastCGI(php),tomcat(jsp),nginx作為方向代理伺服器存在。

所以實際使用中,個人覺得至少有三個匹配規則定義,如下:
#直接匹配網站根,透過域名訪問網站首頁比較頻繁,使用這個會加速處理,官網如是說。
#這裡是直接轉發給後端應用伺服器了,也可以是一個靜態首頁
# 第一個必選規則
location = / {
    proxy_pass
}
# 第二個必選規則是處理靜態檔案請求,這是nginx作為http伺服器的強項
# 有兩種配置模式,目錄匹配或字尾匹配,任選其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
#第三個規則就是通用規則,用來轉發動態請求到後端應用伺服器
#非靜態檔案請求就預設是動態請求,自己根據實際把握
#畢竟目前的一些框架的流行,帶.php,.jsp字尾的情況很少了
location / {
    proxy_pass
}


2.3 ReWrite語法
last – 基本上都用這個Flag。
break – 中止Rewirte,不在繼續匹配
redirect – 返回臨時重定向的HTTP狀態302
permanent – 返回永久重定向的HTTP狀態301
1、下面是可以用來判斷的表示式:
-f和!-f用來判斷是否存在檔案
-d和!-d用來判斷是否存在目錄
-e和!-e用來判斷是否存在檔案或目錄
-x和!-x用來判斷檔案是否可執行
2、下面是可以用作判斷的全域性變數
例:
$host:localhost
$server_port:88
$request_uri:
$document_uri:/test1/test2/test.php
$document_root:D:\nginx/html
$request_filename:D:\nginx/html/test1/test2/test.php

2.4 Redirect語法
server {
listen 80;
server_name start.igrow.cn;
index index.html index.php;
root html;
if ($http_host !~ “^star\.igrow\.cn$&quot {
rewrite ^(.*) redirect;
}
}

2.5 防盜鏈
location ~* \.(gif|jpg|swf)$ {
valid_referers none blocked start.igrow.cn sta.igrow.cn;
if ($invalid_referer) {
rewrite ^/
}
}

2.6 根據檔案型別設定過期時間
location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) {
expires 1h;
break;
}
}

2.7 禁止訪問某個目錄
location ~* \.(txt|doc)${
root /data/www/wwwroot/linuxtone/test;
deny all;
}
一些可用的全域性變數:
$args
$content_length
$content_type
$document_root
$document_uri
$host
$http_user_agent
$http_cookie
$limit_rate
$request_body_file
$request_method
$remote_addr
$remote_port
$remote_user
$request_filename
$request_uri
$query_string
$scheme
$server_protocol
$server_addr
$server_name
$server_port
$uri


2.8 Nginx靜態檔案(css,js,jpg等等web靜態資源)
vim /usr/local/nginx/conf/nginx.conf
  server {
        listen       80;
        server_name  localhost;
        open_file_cache max=10000 inactive=60s;


        location /group1/M00 {
            root   /data/fastdfs/data;
            ngx_fastdfs_module;
        }


        location /css {
            root   plocc_static;
            include gzip.conf;
        }


        location /common {
            root   plocc_static;
            include gzip.conf;
        }


2.9 nginx 轉發工程的日誌檔案
去nginx.conf配置檔案裡面去看訪問日誌,如下:
vim nginx.conf
       location ~* ^/mobileWeb/.*$ {
           include deny.conf;


           proxy_pass
           include proxy.conf;


           error_log  logs/mobileweb_error.log error;
           access_log  logs/mobileweb_access.log  main;


           include gzip.conf;
        }
再去logs目錄檢視日誌檔案,如下:
[root@xx logs]# ll /usr/local/nginx/logs/mobileweb*
-rw-r--r--. 1 root root 10946 7月  18 10:36 /usr/local/nginx/logs/mobileweb_access.log
-rw-r--r--. 1 root root  1628 7月  18 10:36 /usr/local/nginx/logs/mobileweb_error.log


3 新增啟動服務
  1. [root@localhost nginx]# cat /etc/init.d/nginx
  2. #!/bin/bash
  3. #chkconfig:2345 70 70
  4. #description:nginx
  5. BIN=/usr/nginx/sbin/nginx
  6. function d_start {
  7.   $BIN || echo -n \"nginx is running\"
  8. }

  9. function d_stop {
  10.   $BIN -s stop || echo -n \"nginx is not running\"
  11. }

  12. function d_reload {
  13.   $BIN -s reload || echo -n \"nginx reload failed\"
  14. }

  15. case $1 in
  16. start)
  17.    echo start nginx
  18.    d_start
  19. ;;
  20. stop)
  21.    echo stop nginx
  22.    d_stop
  23. ;;
  24. reload)
  25.    echo reload nginx
  26.    d_reload
  27. ;;
  28. restart)
  29.    echo restart nginx
  30.    d_stop
  31.    echo sleep 5s
  32.    sleep 5
  33.    d_start
  34. ;;
  35. *)
  36.    echo \"Usage: nginx [start | stop |reload |restart]\"
  37. ;;

  38. esac
  39. exit 0
啟動: service nginx start;


4 製作證照Key。
4.1.首先要生成伺服器端的私鑰(key檔案):
openssl genrsa -des3 -out server.key 2048

Enter pass phrase for server.key:gongsilong0617

4.2.用server.key生成一個證照:
openssl req -new -key server.key -out server.csr
pass phrase: gongsilong0617

[root@localhost ssl]# openssl req -new -key server.key -out server.csr
Enter pass phrase for server.key:
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) [GB]:cn
State or Province Name (full name) [Berkshire]:shanghai
Locality Name (eg, city) [Newbury]:shanghai
Organization Name (eg, company) [My Company Ltd]:gongsilong
Organizational Unit Name (eg, section) []:business
Common Name (eg, your name or your server's hostname) []:ops
Email Address []:mch@gongsilong.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:gongsilong0617
An optional company name []:gongsilong
[root@localhost ssl]#

4.3. 對客戶端也作同樣的命令生成key及csr檔案
openssl genrsa -des3 -out client.key 2048
pass phrase: plclient0618

[root@localhost client]# openssl req -new -key client.key -out client.csr
Enter pass phrase for client.key:
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) [GB]:cn
State or Province Name (full name) [Berkshire]:shanghai
Locality Name (eg, city) [Newbury]:shanghai
Organization Name (eg, company) [My Company Ltd]:gongsilong
Organizational Unit Name (eg, section) []:business
Common Name (eg, your name or your server's hostname) []:ops
Email Address []:mch@gongsilong.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:plclient0618
An optional company name []:gongsilong

4.4 生成的CSR證照檔案必須有CA的簽名才可形成證照.這裡製作自己的CA 這時生成一個KEY檔案ca.key 和根證照ca.crt
pass phrase: gongsilong0617

[root@localhost ssl]# openssl req -new -x509 -nodes -keyout ca.key -out ca.crt
Generating a 1024 bit RSA private key
.......++++++
................++++++
writing new private key to 'ca.key'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
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) [GB]:cn
State or Province Name (full name) [Berkshire]:shanghai
Locality Name (eg, city) [Newbury]:
writing new private key to 'ca.key'Organization Name (eg, company) [My Company Ltd]:
[root@localhost ssl]# openssl req -new -x509 -keyout ca.key -out ca.crt
Generating a 1024 bit RSA private key
..............++++++
..................................................++++++
writing new private key to 'ca.key'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
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) [GB]:cn
State or Province Name (full name) [Berkshire]:shanghai
Locality Name (eg, city) [Newbury]:shanghai
Organization Name (eg, company) [My Company Ltd]:gongsilong
Organizational Unit Name (eg, section) []:business
Common Name (eg, your name or your server's hostname) []:ops
Email Address []:mch@gongsilong.com
[root@localhost ssl]# 
[root@localhost ssl]# mch@gongsilong.com
-bash: mch@gongsilong.com: command not found
[root@localhost ssl]# 

簽署證照準備工作:
[root@mail ssl]# vim /etc/pki/tls/openssl.cnf
#dir            = ../../CA      //修改如下
dir             = /etc/pki/plocc/CA


touch /etc/pki/plocc/CA/{index.txt,serial} 
[root@localhost ssl]# ll /etc/pki/plocc/CA/
總計 0
-rw-r--r-- 1 root root 0 06-18 10:47 index.txt
-rw-r--r-- 1 root root 0 06-18 10:47 serial
[root@localhost ssl]# echo 01 > /etc/pki/plocc/CA/serial
[root@localhost ssl]# mkdir /etc/pki/plocc/CA/newcerts

4.5 用生成的CA的證照(ca.crt)為剛才生成的server.csr,client.csr檔案簽名
pass phrase:gongsilong0617
openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key 

[root@localhost ssl]# openssl ca -in server.csr -out server.crt -cert ca.crt -keyfile ca.key 
Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for ca.key:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Jun 18 04:04:09 2014 GMT
            Not After : Jun 18 04:04:09 2015 GMT
        Subject:
            countryName               = cn
            stateOrProvinceName       = shanghai
            organizationName          = baolong
            organizationalUnitName    = business
            commonName                = ops
            emailAddress              = mch@gongsilong.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                52:6A:D9:56:CB:2B:DA:E3:9A:18:CC:FE:4D:A1:8C:21:86:55:D5:11
            X509v3 Authority Key Identifier: 
                keyid:4E:F5:29:7F:6B:AD:11:EF:FC:44:CC:76:1D:B0:B9:F7:4B:9D:CB:93

Certificate is to be certified until Jun 18 04:04:09 2015 GMT (365 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
[root@localhost ssl]# 

[root@localhost ssl]# openssl ca -in client.csr -out client.crt -cert ca.crt -keyfile ca.key 
Using configuration from /etc/pki/tls/openssl.cnf
Enter pass phrase for ca.key:
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 2 (0x2)
        Validity
            Not Before: Jun 18 04:10:40 2014 GMT
            Not After : Jun 18 04:10:40 2015 GMT
        Subject:
            countryName               = cn
            stateOrProvinceName       = shanghai
            organizationName          = baolong
            organizationalUnitName    = business
            commonName                = ops
            emailAddress              = mch@gongsilong.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                E2:64:97:DC:A6:2B:85:53:5F:6C:5C:8D:1F:EB:59:C8:2C:66:C5:10
            X509v3 Authority Key Identifier: 
                keyid:4E:F5:29:7F:6B:AD:11:EF:FC:44:CC:76:1D:B0:B9:F7:4B:9D:CB:93


Certificate is to be certified until Jun 18 04:10:40 2015 GMT (365 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
[root@localhost ssl]# 


[PS]:附帶功能:
另外,這個certificate是BASE64形式的,要轉成PKCS12才能裝到IE,/NETSCAPE上.轉換如下:
雙擊安裝就行
 openssl pkcs12 -export -clcerts -in client.crt -inkey client.key -out client.p12
這個是ISO 需要的證照格式
openssl x509 -in client.crt -out client.cer
這個是android 需要的證照格式。
[root@mail ssl]# openssl pkcs12 -export -in client.crt -inkey client.key -out  client.pfx
Enter pass phrase for client.key:      //客戶端私鑰密碼
Enter Export Password:             //pfx檔案匯入要求的密碼
Verifying - Enter Export Password:

[root@localhost conf]# service nginx stop
stop nginx
Enter PEM pass phrase:
phrase is too short, needs to be at least 4 chars
Enter PEM pass phrase:
phrase is too short, needs to be at least 4 chars
Enter PEM pass phrase:

nginx啟動SSL預設不輸入密碼
如果nginx配置了SSL,在每次啟動nginx的時候都會需要你手動輸入證照的密碼,如果不想輸入,可以
cp server.key server.key.orig
openssl rsa -in server.key.orig -out server.key
這樣啟動nginx的時候就不需要輸入密碼了。

[root@localhost ssl]# cp server.key server.key.orig
[root@localhost ssl]# openssl rsa -in server.key.orig -out server.key
Enter pass phrase for server.key.orig:
unable to load Private Key
20487:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:325:
20487:error:0906A065:PEM routines:PEM_do_header:bad decrypt:pem_lib.c:425:
[root@localhost ssl]# 

這裡奇怪,一開始通不過,但是過了15分鐘後,在執行一遍,輸入密碼,又透過了,如下所示:
[root@localhost ssl]# openssl rsa -in server.key.orig -out server.key
Enter pass phrase for server.key.orig:
writing RSA key
[root@localhost ssl]# 

當然也可以保留密碼,改用expect的方式,這個可以參考expect自動登入SSH的方法,下次有時間再整理貼上來

5 靜態檔案地址對映 nginx
location = userWeb/userCenter/findConsultList.htm {
           rewrite ^.*$
        }


 # add by tim begin ...
        location ~* ^/svn/(.*) {
           rewrite ^.*$
        }
        # add by tim end .. 



conference:http://blog.chinaunix.net/uid-22006903-id-149747.html

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29734436/viewspace-1223398/,如需轉載,請註明出處,否則將追究法律責任。

相關文章