首页 > 代码库 > Nginx安装学习使用详细记录

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 执行安装
  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
}
那么产生的效果如下:
访问根目录/, 比如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
1、下面是可以用来判断的表达式:
-f和!-f用来判断是否存在文件
-d和!-d用来判断是否存在目录
-e和!-e用来判断是否存在文件或目录
-x和!-x用来判断文件是否可执行
2、下面是可以用作判断的全局变量
例: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$&quot {
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 添加启动服务
  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 .. 


来源地址:http://blog.itpub.net/26230597/abstract/1/