nginx [engine x]是Igor Sysoev编写的一个HTTP和反向代理服务器,另外它也可以作为邮件代理服务器。 它从2004开始已经在众多流量很大的俄罗斯网站上使用,之前apache的时候已经看过他的市场占有率正在逐步的向上提升。

基本的HTTP服务器特性

 处理静态文件,索引文件以及自动索引;打开文件描述符缓存;
 使用缓存加速反向代理;简单负载均衡以及容错;
 远程FastCGI服务的缓存加速支持;简单的负载均衡以及容错;
 模块化的架构。过滤器包括gzip压缩、ranges支持、chunked响应、XSLT,SSI以及图像缩放。在SSI 过滤器中,一个包含多个SSI的页面,如果经由FastCGI或反向代理处理,可被并行处理;
 支持SSL,TLS SNI。

其他的HTTP服务器特性

 基于名字和IP的虚拟主机;
 Keep-alive和pipelined连接支持;
 灵活的配置;
 重新加载配置以及在线升级时,不需要中断正在处理的请求;
 自定义访问日志格式,带缓存的日志写操作以及快速日志轮转;
 3xx-5xx错误代码重定向;
 重写(rewrite)模块;
 基于客户端IP地址和HTTP基本认证机制的访问控制;
 支持PUT、DELETE、MKCOL、COPY以及MOVE方法;
 支持FLV流和MP4流;
 速度限制;
 来自同一地址的同时连接数或请求数限制;
 嵌入Perl语言。

nginx的安装
www.nginx.org下载软件包:
 

 
  
  1. # yum -y install pcre-devel  
  2. # groupadd -r nginx  
  3. # useradd -r -g nginx -s /sbin/nologin -M nginx
  4.  
  5. # tar xf nginx-1.2.2.tar.gz
    # cd nginx-1.2.2
  6. #  ./configure \  
  7.   --prefix=/usr \  
  8.   --sbin-path=/usr/sbin/nginx \  
  9.   --conf-path=/etc/nginx/nginx.conf \  
  10.   --error-log-path=/var/log/nginx/error.log \  
  11.   --http-log-path=/var/log/nginx/access.log \  
  12.   --pid-path=/var/run/nginx/nginx.pid  \  
  13.   --lock-path=/var/lock/nginx.lock \  
  14.   --user=nginx \  
  15.   --group=nginx \  
  16.   --with-http_ssl_module \  
  17.   --with-http_flv_module \  
  18.   --with-http_stub_status_module \  
  19.   --with-http_gzip_static_module \  
  20.   --http-client-body-temp-path=/var/tmp/nginx/client/ \  
  21.   --http-proxy-temp-path=/var/tmp/nginx/proxy/ \  
  22.   --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \  
  23.   --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \  
  24.   --http-scgi-temp-path=/var/tmp/nginx/scgi \  
  25.   --with-pcre  
  26. # make && make install 

为nginx提供启动脚本:
/etc/rc.d/init.d/nginx,内容如下:
 

 
  
  1. #!/bin/sh  
  2. #  
  3. # nginx - this script starts and stops the nginx daemon  
  4. #  
  5. # chkconfig:   - 85 15   
  6. # description:  Nginx is an HTTP(S) server, HTTP(S) reverse \  
  7. #               proxy and IMAP/POP3 proxy server  
  8. # processname: nginx  
  9. # config:      /etc/nginx/nginx.conf  
  10. # config:      /etc/sysconfig/nginx  
  11. # pidfile:     /var/run/nginx.pid  
  12.    
  13. # Source function library.  
  14. . /etc/rc.d/init.d/functions  
  15.    
  16. # Source networking configuration.  
  17. . /etc/sysconfig/network  
  18.    
  19. # Check that networking is up.  
  20. [ "$NETWORKING" = "no" ] && exit 0  
  21.    
  22. nginx="/usr/sbin/nginx" 
  23. prog=$(basename $nginx)  
  24.    
  25. NGINX_CONF_FILE="/etc/nginx/nginx.conf" 
  26.    
  27. [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx  
  28.    
  29. lockfile=/var/lock/subsys/nginx  
  30.    
  31. make_dirs() {  
  32.    # make required directories  
  33.    user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`  
  34.    options=`$nginx -V 2>&1 | grep 'configure arguments:'`  
  35.    for opt in $options; do  
  36.        if [ `echo $opt | grep '.*-temp-path'` ]; then  
  37.            value=`echo $opt | cut -d "=" -f 2`  
  38.            if [ ! -d "$value" ]; then  
  39.                # echo "creating" $value  
  40.                mkdir -p $value && chown -R $user $value  
  41.            fi  
  42.        fi  
  43.    done  
  44. }  
  45.    
  46. start() {  
  47.     [ -x $nginx ] || exit 5  
  48.     [ -f $NGINX_CONF_FILE ] || exit 6  
  49.     make_dirs  
  50.     echo -n $"Starting $prog: "  
  51.     daemon $nginx -c $NGINX_CONF_FILE  
  52.     retval=$?  
  53.     echo  
  54.     [ $retval -eq 0 ] && touch $lockfile  
  55.     return $retval  
  56. }  
  57.    
  58. stop() {  
  59.     echo -n $"Stopping $prog: "  
  60.     killproc $prog -QUIT  
  61.     retval=$?  
  62.     echo  
  63.     [ $retval -eq 0 ] && rm -f $lockfile  
  64.     return $retval  
  65. }  
  66.    
  67. restart() {  
  68.     configtest || return $?  
  69.     stop  
  70.     sleep 1  
  71.     start  
  72. }  
  73.    
  74. reload() {  
  75.     configtest || return $?  
  76.     echo -n $"Reloading $prog: "  
  77.     killproc $nginx -HUP  
  78.     RETVAL=$?  
  79.     echo  
  80. }  
  81.    
  82. force_reload() {  
  83.     restart  
  84. }  
  85.    
  86. configtest() {  
  87.   $nginx -t -c $NGINX_CONF_FILE  
  88. }  
  89.    
  90. rh_status() {  
  91.     status $prog  
  92. }  
  93.    
  94. rh_status_q() {  
  95.     rh_status >/dev/null 2>&1  
  96. }  
  97.    
  98. case "$1" in  
  99.     start)  
  100.         rh_status_q && exit 0  
  101.         $1  
  102.         ;;  
  103.     stop)  
  104.         rh_status_q || exit 0  
  105.         $1  
  106.         ;;  
  107.     restart|configtest)  
  108.         $1  
  109.         ;;  
  110.     reload)  
  111.         rh_status_q || exit 7  
  112.         $1  
  113.         ;;  
  114.     force-reload)  
  115.         force_reload  
  116.         ;;  
  117.     status)  
  118.         rh_status  
  119.         ;;  
  120.     condrestart|try-restart)  
  121.         rh_status_q || exit 0  
  122.             ;;  
  123.     *)  
  124.         echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"  
  125.         exit 2  
  126. esac 

# chmod +x /etc/rc.d/init.d/nginx
# service nginx start


配置文件,注意Nginx的配置文件都是以;结尾的:

 
  
  1. # egrep -v "^[[:space:]]*#|^$" /etc/nginx/nginx.conf  
  2. worker_processes  1;  
  3. events {  
  4.     worker_connections  1024;  
  5. }  
  6. http {  
  7.     include       mime.types;  
  8.     default_type  application/octet-stream;  
  9.     sendfile        on;  
  10.     keepalive_timeout  65;  
  11.     server {  
  12.         listen       80;  
  13.         server_name  localhost;  
  14.         location / {  
  15.             root   html;  
  16.             index  index.html index.htm;  
  17.         }  
  18.         error_page   500 502 503 504  /50x.html;  
  19.         location = /50x.html {  
  20.             root   html;  
  21.         }  
  22.     }  

其中worker_processes和events是全局配置:
worker_processes 是指Nginx开启的进程数,建议进程数和CPU的个数一样即可

http中是对服务器的配置
server类似apache的虚拟主机,可以指定多可,这里是默认主机

location / 这里是没加=号,代表匹配这个/目录下的所有文件,这里的/是相对编译安装指定--prefix=/usr的路径的
location = /50x.html 仅匹配当个文件,明确指匹配文件本身,或目录本身。

这里还有“~”和“~*”:“~”代表匹配时区别大小写,而“~*”代表不区别大小写
“^~” 表示不作正则表达式匹配

当然配置文件中还有一些注释的也需要了解下

 
  
  1. #location ~ \.php$ {  
  2.         #    proxy_pass   http://127.0.0.1;  
  3.         #}  
  4.  
  5.         # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000  
  6.         #  
  7.         #location ~ \.php$ {  
  8.         #    root           html;  
  9.         #    fastcgi_pass   127.0.0.1:9000;  
  10.         #    fastcgi_index  index.php;  
  11.         #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;  
  12.         #    include        fastcgi_params;  
  13.         #} 

这里是整合PHP时候需要了解的。其中:
proxy_pass   http://127.0.0.1; 表示反向代理的。

以下表示使用fastcgi模式的
#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;

基于ip的虚拟主机:
修改/etc/nginx/nginx.conf的如下内容
 

 
  
  1. ……  
  2.     server {  
  3.         listen      192.168.80.140:80;  
  4.         server_name  localhost;  
  5.         location / {  
  6.             root   html;  
  7.             index  index.html index.htm;  
  8.         }  
  9.         error_page   500 502 503 504  /50x.html;  
  10.         location = /50x.html {  
  11.             root   html;  
  12.         }  
  13.     }  
  14.  server {  
  15.  listen  192.168.80.141:80;  
  16.  server_name www.peace.com;  
  17.  location / {  
  18.   root html/peace.com;  
  19.   index index.html;  
  20.   }   
  21.  }  

# mkdir /usr/html/peace.com
# echo "peace.com" > /usr/html/peace.com/index.html
# echo "hello" > /usr/html/index.html
# service nginx restart

基于域名的虚拟主机只需将 server_name 改成不同即可
基于端口的话就将更改listen 后面的监听端口即可

这里的root定义路径的,也可以写成alias 定义别名

也可以指定访问控制,可以控制网段,ip 如下:
location / {
 deny 192.168.0.1/24
 deny 192.168.0.100
 allow all

}

启动StubStatus 模块配置,这个模块式做工作状态统计功能的,如下我在配置文件中开启,一个server中可以有多个location,这里的access_log 也可以指定路径的:

 
  
  1. ……  
  2. server {  
  3.         listen   192.168.80.141:80;  
  4.         server_name     www.peace.com;  
  5.         location / {  
  6.                 alias   /web/www/;  
  7.                 index   index.html;  
  8.                 }  
  9.         location /stubstatus {  
  10.                 stub_status     on;  
  11.                 access_log      off;  
  12.                 }  
  13.         }  
  14. …… 

访问http://www.peace.com/stubstatus即可:


Active connections: 2 表示当前活跃的连接数
第三行的数字分别表示位:总共处理连接数,成功握手数,总共处理请求数
Reading: 表示Nginx读取客户端Header信息数,
Writing: 表示Nginx返回给客户端的Header信息数
Waiting: 表示Nginx已经处理完,正等下次请求是的驻留连接数,


基于用户认证:

 
  
  1. server {  
  2.         listen   192.168.80.141:80;  
  3.         server_name     www.peace.com;  
  4.         location / {  
  5.                 alias   /web/www/;  
  6.                 index   index.html;  
  7.                 auth_basic "Restricted";  
  8.                 auth_basic_user_file /etc/nginx/.htpasswd;  
  9.                 }  
  10.         location /stubstatus {  
  11.                 stub_status     on;  
  12.                 access_log      off;  
  13.                 }  
  14.         } 

这里值得注意的是nginx没有htpasswd命令来生成文件,所以得用apache的命令,yum安装httpd使用命令即可
# htpasswd -cm /etc/nginx/.htpasswd redhat //第一次加-c创建,之后就不再需要了

我们访问www.peace.com是已经要求要密码了,输入即可访问了:


这里是基于明文的,下面设置https的访问
首先先建立CA:

 
  
  1. # vim /etc/pki/tls/openssl.cnf   
  2. # cd /etc/pki/CA/  
  3. # (umask 077; openssl genrsa 1024 > private/cakey.pem)  
  4. # openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365  
  5.             Country Name (2 letter code) [GB]:CN  
  6.             State or Province Name (full name) [Berkshire]:BJ  
  7.              Locality Name (eg, city) [Newbury]:beijing  
  8.              Organization Name (eg, company) [My Company Ltd]:peace  
  9.              Organizational Unit Name (eg, section) []:Tech  
  10.              Common Name (eg, your name or your server's hostname) []:ca.peace.com  
  11.              Email Address []:admin@peace.com  
  12. # mkdir certs newcerts crl  
  13. # touch index.txt  
  14. # echo 01 > serial  
  15.  
  16.  
  17. # mkdir -p /etc/nginx/ssl  
  18. # cd /etc/nginx/ssl  
  19. # (umask 077 ; openssl genrsa 1024 > nginx.key)  
  20. # openssl req -new -key nginx.key -out nginx.csr  
  21.               Country Name (2 letter code) [GB]:CN  
  22.               State or Province Name (full name) [Berkshire]:BJ  
  23.               Locality Name (eg, city) [Newbury]:beijing  
  24.              Organization Name (eg, company) [My Company Ltd]:peace  
  25.              Organizational Unit Name (eg, section) []:Tech  
  26.               Common Name (eg, your name or your server's hostname) []:www.peace.com  
  27.                Email Address []:admin@peace.com  
  28. # openssl ca -in nginx.csr -out nginx.crt  
  29.             Certificate is to be certified until Jul 13 08:22:55 2013 GMT (365 days)  
  30.              Sign the certificate? [y/n]:y  
  31.              1 out of 1 certificate requests certified, commit? [y/n]y  

编辑nginx配置文件修改如下信息
 

 
  
  1. server {  
  2.         listen   192.168.80.141:443;  
  3.         server_name     www.peace.com;  
  4.  
  5.         ssl                  on;  
  6.         ssl_certificate      /etc/nginx/ssl/nginx.crt;  
  7.         ssl_certificate_key  /etc/nginx/ssl/nginx.key;  
  8.  
  9.         ssl_session_timeout  5m;  
  10.  
  11.         ssl_protocols  SSLv2 SSLv3 TLSv1;  
  12.         ssl_ciphers  HIGH:!aNULL:!MD5;  
  13.         ssl_prefer_server_ciphers   on;  
  14.  
  15.         location / {  
  16.                 alias   /web/www/;  
  17.                 index   index.html;  
  18.                 }  
  19.         location /stubstatus {  
  20.                 stub_status     on;  
  21.                 access_log      off;  
  22.                 }  
  23.         } 

这时候访问https://www.peace.com/https://www.peace.com/stubstatus都是加密的,不过证书不是信任的这里导入即可,之前有介绍这里不讲解了