前言:
选择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 执行安装

  • tar -xvf nginx-1.4.2.tar.gz
  • cd nginx-1.4.2
  • ./configure --prefix=/usr/nginx --with-http_stub_status_module --with-debug --with-http_realip_module --with-http_ssl_module


  • [root@localhost nginx-1.4.2]# make install
  • ......
  • test -d \'/usr/nginx/logs\' || mkdir -p \'/usr/nginx/logs\'
  • test -d \'/usr/nginx/logs\' || mkdir -p \'/usr/nginx/logs\'
  • test -d \'/usr/nginx/html\' || cp -R html \'/usr/nginx\'
  • 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会增高。

  • [root@lb-net-2 ~]# ps -eaf|grep nginx
  • root 2221 1382 0 18:06 pts/0 00:00:00 grep nginx
  • root 16260 1 0 Jun18 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
  • nobody 16261 16260 0 Jun18 ? 00:01:26 nginx: worker process 
  • nobody 16262 16260 0 Jun18 ? 00:01:32 nginx: worker process 
  • nobody 16263 16260 0 Jun18 ? 00:01:25 nginx: worker process 
  • nobody 16264 16260 0 Jun18 ? 00:01:33 nginx: worker process 
  • nobody 16265 16260 0 Jun18 ?

     00:01:32 nginx: worker process 

  • nobody 16266 16260 0 Jun18 ? 00:01:24 nginx: worker process 
  • nobody 16267 16260 0 Jun18 ?

     00:01:32 nginx: worker process 

  • nobody 16268 16260 0 Jun18 ?

     00:01:23 nginx: worker process 

  • nobody 16269 16260 0 Jun18 ?

     00:01:32 nginx: worker process 

  • nobody 16270 16260 0 Jun18 ? 00:01:26 nginx: worker process 
  • nobody 16271 16260 0 Jun18 ?

     00:01:32 nginx: worker process 

  • nobody 16272 16260 0 Jun18 ? 00:01:25 nginx: worker process 
  • nobody 16273 16260 0 Jun18 ? 00:01:26 nginx: worker process 
  • nobody 16274 16260 0 Jun18 ? 00:01:32 nginx: worker process 
  • nobody 16275 16260 0 Jun18 ? 00:01:32 nginx: worker process 
  • nobody 16276 16260 0 Jun18 ?

     00:01:33 nginx: worker process 

  • nobody 16277 16260 0 Jun18 ? 00:01:24 nginx: worker process 
  • nobody 16278 16260 0 Jun18 ? 00:01:24 nginx: worker process 
  • nobody 16279 16260 0 Jun18 ? 00:01:30 nginx: worker process 
  • nobody 16280 16260 0 Jun18 ?

     00:01:24 nginx: worker process 

  • nobody 16281 16260 0 Jun18 ? 00:01:32 nginx: worker process 
  • nobody 16282 16260 0 Jun18 ? 00:01:32 nginx: worker process 
  • nobody 16283 16260 0 Jun18 ?

     00:01:25 nginx: worker process 

  • 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 转发project的日志文件
    去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 加入启动服务

  • [root@localhost nginx]# cat /etc/init.d/nginx
  • #!/bin/bash
  • #chkconfig:2345 70 70
  • #description:nginx
  • BIN=/usr/nginx/sbin/nginx
  • function d_start {
  •   $BIN || echo -n \"nginx is running\"
  • }

  • function d_stop {
  •   $BIN -s stop || echo -n \"nginx is not running\"
  • }

  • function d_reload {
  •   $BIN -s reload || echo -n \"nginx reload failed\"
  • }

  • case $1 in
  • start)
  •    echo start nginx
  •    d_start
  • ;;
  • stop) 
  •    echo stop nginx
  •    d_stop
  • ;;
  • reload)
  •    echo reload nginx
  •    d_reload
  • ;;
  • restart)
  •    echo restart nginx
  •    d_stop
  •    echo sleep 5s
  •    sleep 5
  •    d_start
  • ;;
  • *) 
  •    echo \"Usage: nginx [start | stop |reload |restart]\"
  • ;;

  • esac
  • 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:      //客户端私钥password
    Enter Export Password:             //pfx文件导入要求的password
    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默认不输入password
    假设nginx配置了SSL,在每次启动nginx的时候都会须要你手动输入证书的password,假设不想输入,能够
    cp server.key server.key.orig
    openssl rsa -in server.key.orig -out server.key
    这样启动nginx的时候就不须要输入password了。

    [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分钟后,在执行一遍,输入password,又通过了,例如以下所看到的:
    [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]# 

    当然也能够保留password。改用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/

    相关文章:

    • 2021-06-20
    • 2022-01-30
    • 2021-10-29
    • 2021-08-12
    • 2021-06-08
    • 2021-07-22
    • 2021-05-02
    • 2021-10-08
    猜你喜欢
    • 2022-12-23
    • 2021-08-20
    • 2021-07-21
    • 2021-07-14
    • 2022-03-05
    • 2022-01-14
    • 2021-11-01
    相关资源
    相似解决方案