Nginx安裝學習使用詳細記錄

選擇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 執行安裝php

  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會增高。css

  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
}
那麼產生的效果以下:
訪問根目錄/, 好比http://localhost/ 將匹配規則A
訪問 http://localhost/login 將匹配規則B,http://localhost/register 則匹配規則H
訪問 http://localhost/static/a.html 將匹配規則C
訪問 http://localhost/a.gif, http://localhost/b.jpg 將匹配規則D和規則E,可是規則D順序優先,規則E不起做用,而 http://localhost/static/c.png 則優先匹配到規則C
訪問 http://localhost/a.PNG 則匹配規則E,而不會匹配規則D,由於規則E不區分大小寫。
訪問 http://localhost/a.xhtml 不會匹配規則F和規則G,http://localhost/a.XHTML不會匹配規則G,由於不區分大小寫。規則F,規則G屬於排除法,符合匹配規則可是不會匹配到,因此想一想看實際應用中哪裏會用到。
訪問 http://localhost/category/id/1111 則最終匹配到規則H,由於以上規則都不匹配,這個時候應該是nginx轉發請求給後端應用服務器,好比FastCGI(php),tomcat(jsp),nginx做爲方向代理服務器存在。

因此實際使用中,我的以爲至少有三個匹配規則定義,以下:
#直接匹配網站根,經過域名訪問網站首頁比較頻繁,使用這個會加速處理,官網如是說。
#這裏是直接轉發給後端應用服務器了,也能夠是一個靜態首頁
# 第一個必選規則
location = / {
    proxy_pass http://tomcat:8080/index
}
# 第二個必選規則是處理靜態文件請求,這是nginx做爲http服務器的強項
# 有兩種配置模式,目錄匹配或後綴匹配,任選其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
#第三個規則就是通用規則,用來轉發動態請求到後端應用服務器
#非靜態文件請求就默認是動態請求,本身根據實際把握
#畢竟目前的一些框架的流行,帶.php,.jsp後綴的狀況不多了
location / {
    proxy_pass http://tomcat:8080/
}


2.3 ReWrite語法
last – 基本上都用這個Flag。
break – 停止Rewirte,不在繼續匹配
redirect – 返回臨時重定向的HTTP狀態302
permanent – 返回永久重定向的HTTP狀態301
一、下面是能夠用來判斷的表達式:
-f和!-f用來判斷是否存在文件
-d和!-d用來判斷是否存在目錄
-e和!-e用來判斷是否存在文件或目錄
-x和!-x用來判斷文件是否可執行
二、下面是能夠用做判斷的全局變量
例:http://localhost:88/test1/test2/test.php
$host:localhost
$server_port:88
$request_uri:http://localhost:88/test1/test2/test.php
$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$" {
rewrite ^(.*) http://star.igrow.cn$1 redirect;
}
}

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

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 http://mobilewebbackend;
           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 添加啓動服務html

  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 ^.*$ http://xx.gongsilong.com/xx/xx/findConsultList.htm;
        }


 # add by tim begin ...
        location ~* ^/svn/(.*) {
           rewrite ^.*$ https://192.123.11.12/$1;
        }
        # add by tim end .....node

 

轉載他人......................linux

相關文章
相關標籤/搜索