一、nginx简介

Nginx ("engine x") 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx 是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。

Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:新浪、网易、腾讯等。

 

二、nginx的结构

一个master主进程和多个worker工作进程。工作进程是单线程的,且不需要特殊授权即可运行;一个worker线程响应多个请求;

以非阻塞、事件驱动机制工作;

支持多种事件驱动机制。如kqueue (FreeBSD 4.1+),epoll (Linux 2.6+),rt signals (Linux 2.2.19+),/dev/poll (Solaris 7 11/99+),select,以及 poll;

支持sendfile (FreeBSD 3.1+),sendfile (Linux 2.2+),sendfile64 (Linux 2.4.21+),和 sendfilev (Solaris 8 7/01+) 

支持文件AIO(异步I/O)

支持mmap(将磁盘上的数据直接以页面的形式映射到用户进程内存中)



三、nginx的功能和特性

nginx具备的基础功能有:

    可用于处理静态资源的web服务器,可以缓存打开的文件描述符;

    可用于反向代理服务器,并且可以缓存静态资源,能够实现负载均衡功能以及实现后端服务器的健康状态监测;

    模块化的设计,不支持非DSO机制(即不能动态加载模块,但apache支持该功能)

    支持多种过滤器如gzip;

    支持SSL和TLS SNI;

 

nginx其他扩展功能:

    支持基于名称和基于IP的虚拟服务器;

    Flexible configuration;灵活的配置;

    支持保持活动连接(keepalive)和支持管线连接

    支持重载配置,无间断程序升级(即在线升级)

    支持rewrite重写功能

    支持基于IP地址访问控制和基于用户的访问控制

    支持3xx的- 5xx错误代码重定向

    支持FLV视频流

    支持限制同个IP地址请求数量(并发数)和速率限制

    支持嵌入式的Perl

    支持可定制的访问日志,日志写入缓存,以及快捷的日志回卷

    支持缓存功能

 


四、nginx作为web服务器的应用

实验前提:
1、本次实验我使用的系统平台为RHEL5.8
2、由于在测试时是基于域名来访问的,因此,需要修改系统上的hosts文件,如:
     192.168.0.104
www.       192.168.0.104

 

 

nginx作为web服务器的应用
1、创建非特权用户
由于nginx在运行时是以非特权用户的方式进行的,因此,在编译安装前需要创建一个非特权用户
[root@localhost ~]#groupadd -r -g 200 nginx
[root@localhost ~]#useradd -r -g 200 -u 200 nginx

 

 

2、编译安装nginx
在这里我使用的linux平台为RHEL5.8,大家可以根据自己的平台选择相应的nginx版本。
nginx的下载地址:http://nginx.org/en/download.html
[root@localhost ~]# tar xf nginx-1.6.2.tar.gz 
[root@localhost ~]# cd nginx-1.6.2
[root@localhost nginx-1.6.2]# ./configure \
  --prefix=/usr \
  --sbin-path=/usr/sbin/nginx \
  --conf-path=/etc/nginx/nginx.conf \
  --error-log-path=/var/log/nginx/error.log \
  --http-log-path=/var/log/nginx/access.log \
  --pid-path=/var/run/nginx/nginx.pid  \
  --lock-path=/var/lock/nginx.lock \
  --user=nginx \
  --group=nginx \
  --with-http_ssl_module \
  --with-http_flv_module \
  --with-http_stub_status_module \
  --with-http_gzip_static_module \
  --http-client-body-temp-path=/var/tmp/nginx/client/ \
  --http-proxy-temp-path=/var/tmp/nginx/proxy/ \
  --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \
  --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
  --http-scgi-temp-path=/var/tmp/nginx/scgi \
  --with-pcre
 在这里对几个参数说明一下,前面的几个参数都比较好理解就不解释了。
 --lock-path=/var/lock/nginx.lock 设定nginx的锁文件
 --user=nginx表示以哪个非特权用户的身份运行nginx程序,这里的nginx就是我们刚刚创建的非特权用户
 --group=nginx表示程序运行时的非特权用户组
 --with-http_ssl_module表示启用ssl模块,使其支持https功能。如果想支持ssl的话,还需要安装openssl。这里我已经安装了。
 --with-http_stub_status_module启用http_stub_status_module模块,可以获取nginx自上次启用以来的工作状态
 --with-http_gzip_static_module启用这个模块可以支持gzip压缩功能,对于响应的文件比较大时,可以先压缩在传输,有利于节省带宽。
 --http-client-body-temp-path=/var/tmp/nginx/client设定http客户端请求临时文件路径
 -http-proxy-temp-path=/var/tmp/nginx/proxy/ 设定http代理临时文件路径
 --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/设定http fastcgi临时文件路径
 --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi设定http  uwsgi临时文件路径
 --http-scgi-temp-path=/var/tmp/nginx/scgi设定http scgi临时文件路径
 --with-pcre   启用pcre库。如果想支持正则表达式,需要安装pcre。由于我的系统上已经安装了pcre,因此,这里就不需要安装了.
 
 然后安装相应的模块
 [root@localhost nginx-1.6.2]#   make && make install
 
 3、为nginx提供SysV风格的脚本
 [root@localhost ~]# vim /etc/rc.d/init.d/nginx

#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid
 
# Source function library.
. /etc/rc.d/init.d/functions
 
# Source networking configuration.
. /etc/sysconfig/network
 
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0
 
nginx="/usr/sbin/nginx"
prog=$(basename $nginx)
 
NGINX_CONF_FILE="/etc/nginx/nginx.conf"
 
[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx
 
lockfile=/var/lock/subsys/nginx
 
make_dirs() {
   # make required directories
   user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}
 
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
 
stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
 
restart() {
    configtest || return $?
    stop
    sleep 1
    start
}
 
reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}
 
force_reload() {
    restart
}
 
configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}
 
rh_status() {
    status $prog
}
 
rh_status_q() {
    rh_status >/dev/null 2>&1
}
 
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac


 为脚本添加执行权限
 [root@localhost ~]# chmod +x /etc/init.d/nginx
 将这个脚本加入到服务列表中
 [root@localhost ~]# chkconfig  --add nginx
 设定为开机自启动
 [root@localhost ~]# chkconfig nginx on
 然后,就可以启动nginx服务了
 [root@localhost ~]# service nginx start
Starting nginx: [  OK  ]

注意:如果将nginx作为web服务器的话,千外不能启动httpd服务,否则,两个服务会争用套接字的。会出现如下错误:
Starting nginx: nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] still could not bind()
[FAILED]


4、修改nginx的配置文件
user  nginx  nginx;                运行nginx程序的属主和属组    
worker_processes  1;

error_log  logs/error.log  info;

pid        logs/nginx.pid;      


events {
    worker_connections  1024;     表示一个worker进程可以处理多少个连接请求
}

 

httpd相关的配置
http {
    include       mime.types; 表示http支持多种类型的文件
    default_type  application/octet-stream;
 
#日志格式
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main; 

    sendfile        on;      

    tcp_nopush     on;        

    tcp_nodelay    on;        

    keepalive_timeout  1;                    


 
下面是用来配置服务器段的,每一个server表示一个虚拟主机。在nginx中虚拟主机只有2种:即基于域名的虚拟主机和基于ip的虚拟主机。没有基于端口的虚拟主机。
    server {
        listen       80;                 
        server_name  ;  

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {         
            root   /www/;   
            autoindex off;   
            index  index.html index.htm;  
   
        }

    }
}


 

 
 
5、配置文件修改后,先创建相应的目录,再检查下配置文件的语法是否正确,然后再启动nginx服务。
创建目录
[root@localhost ~]# mkdir  /www/
[root@localhost ~]# vim   /www//index.html 
<h1>test nginx</h1>

检查nginx配置文件的语法是否正确,可以使用如下命令:
[root@localhost ~]# nginx  -t

如果配置文件没有任何问题,则可以启动服务了。
[root@localhost ~]# service nginx start

 

6、测试,访问默认主页是否正常
如果是在浏览器中输入的是服务器的主机名称,则还需要在本机的hosts文件添加主机名称和ip的对应条目才行。在这里我是在window主机上进行测试的,因此,需要在windows系统上的hosts文件中添加如下对应行:
    192.168.0.104
添加完成后,在进行页面测试,测试结果如下:

高性能的web服务器nginx_nginx简介   nginx



7、基于ip的认证

有时候我们需要设定特定的ip才可以访问,以保证服务器的安全性。

基于ip的访问规则是从上到下来检查,一旦匹配则立即终止检查。
设定基于ip的认证命令需要在location中设定,如:
location  / {
            root   /www/;
            autoindex off; 
            index  index.html index.htm;
            deny  192.168.0.0/24;     

            allow 127.0.0.1;

            allow all;

}

默认是允许所有ip访问。这里我的ip是位于192.168.0.0/24的网络中的。

测试结果如下:

高性能的web服务器nginx_nginx简介   nginx_02

 
8、基于用户的认证
基于用户的认证命令也可以在location中设定,如:
location  / {
            root   /www/;
            index  index.html index.htm;
            auth_basic  "Restrice..."    这个命令是用来设置提示语的
            auth_basic_user_file  /etc/nginx/userfile    

            这个命令是用来设定基于用户认证时的用户和密码所在文件
  }


在nginx中,基于用户认证方式中的用户和密码文件是通过htpasswd这个命令来创建的,而htpasswd是httpd自带的程序,因此,要想使用htpasswd来创建用户和密码,需要先安装httpd程序。
# yum  -y  install  httpd
# chkconfig httpd off
# service httpd  stop

使用htpasswd命令创建用户和密码
# htpasswd -c -m /etc/nginx/userfile xsl  

注意,第一次创建用户时需要指定-c参数,以后就不需要了。

创建完成之后,还需要重新加载nginx。不需要重启。
[root@localhost ~]# service  nginx  reload

测试访问http://ww.,测试结果如下:

高性能的web服务器nginx_nginx简介   nginx_03

 将用户和密码输入后,显示的结果为:

高性能的web服务器nginx_nginx简介   nginx_04

 



 

9、错误页面重定向

错误重定向指的是当访问错误时,nginx的响应状态码如果属于error_page指令中定义的话,则将后续定义的uri中的信息响应给客户端。通常用于提示功能。

可以在location中添加如下信息:

error_page  404       404.html;

当错误页面指令定义在location中时,其错误页面(这里是404.html)文件必须要位于指定目录下。

或者在server{}段添加如下信息也可以:

error_page   404  500 502 503 504 /404.html;

location = /404.html {

      root   /html/error;

}

404.html文件必须要位于指定的url下,在这里位于"/"目录下

测试访问一个不存在的页面如http:///20.html。测试结果如下:

高性能的web服务器nginx_nginx简介   nginx_05

 


 

10、 开启nginx的工作状态监控功能
如果需要查看nginx的工作状态信息,还可以设置相关的状态指令。
location  /status {
  stub_status  on;  

}

开启nginx的状态监控功能。不过需要注意的时,如果要设置查看nginx工作状态信息,除了需要启动这个命令之外,更重要的是启用http_stub_status_module这个模块。不过我们在编译时已经启用了这个模块。 


测试访问http:///status,测试结果如下:

高性能的web服务器nginx_nginx简介   nginx_06

其中这些参数意思如下:
Active connection:#  表示所有的活动连接数。

server后面有三个数字(如5 5 6)分别表示如下意思:
第一个数字(如5)表示已经接受的连接数
第二个数字(如5)表示已经成功处理的连接数
第三个数字(如6)表示已经处理的总请求数

因此,平均每个连接处理的请求数=总请求数/接受的连接数


Reading:#    表示nginx正在读取其客户端报文中的header个数
Writing:#    表示正在处理请求个数或正在响应给客户端的header个数
Waiting:#  在keep-alive中,该值=活动连接数-(reading+writing),表示nginx已经处理完,等待下一个请求指令的驻留连接数。



11、启用压缩功能

nginx的压缩功能是由http_gzip_static_module这个模块提供的,如果你在编译安装nginx时,提供了--with-http_gzip_static_module的话,那么你的nginx就支持压缩功能。在nginx上启用压缩功能,可以在响应报文给客户端时,可以对某些文件进行压缩然后在响应给客户端,这样可以节省网络带宽及减少网络IO。

gzip压缩指令可以工作在http段、server段和location段中。

在http{}段内添加如下功能,以启用压缩功能

http {

    ...

    gzip  on;

    gzip_buffers 4 8K;

    gzip_min_length 1k;

    gzip_http_version 1.1;

    gzip_comp_level 6;

    gzip_types text/plain application/x-javascript text/css text/html application/xml;




12、定义基于ssl协议的虚拟主机。即https协议的配置
首先服务器端创建CA证书
[root@localhost CA]# (umask 077;openssl genrsa -out /etc/pki/CA/private/cakey.pem  2048)   创建私钥
[root@localhost CA]# openssl req -new -x509  -key /etc/pki/CA/private/cakey.pem  -out /etc/pki/CA/cacert.pem -days 3650   创建CA证书
[root@localhost CA]# echo 01 > serial
[root@localhost CA]# touch index.txt
[root@localhost CA]# mkdir  cert  crl  newcerts

在服务器端创建私钥
[root@localhost ~]# mkdir /etc/nginx/ssl
[root@localhost ~]# cd /etc/nginx/ssl/
[root@localhost ssl]# (umask 077;openssl genrsa -out nginx.key 2048 )
生成颁发请求文件
[root@localhost ssl]# openssl req -new -key nginx.key -out nginx.csr
CA为颁发请求文件签署成为证书
[root@localhost ssl]# openssl ca -in nginx.csr -out nginx.crt -days 3650

编辑配置文件/etc/nginx/nginx.conf
将鼠标定位到最后一个server段所在行,使用如下命令来去掉前面的"#"号
.,$-1s/^\([[:space:]]*\)#/\1/g
 
   下面是关于https的配置部分
   server {
        listen       443 ssl;     监听端口
        server_name  www.;   服务器名称

        ssl_certificate      /etc/nginx/ssl/nginx.crt;   证书
        ssl_certificate_key  /etc/nginx/ssl/nginx.key;  私钥

        ssl_session_cache    shared:SSL:1m;  ssl会话缓存时长
        ssl_session_timeout  5m;             会话超时时间

        ssl_ciphers  HIGH:!aNULL:!MD5;  加密算法
        ssl_prefer_server_ciphers  on;  是否允许服务器端选择倾向性的加密算法

        location / {
            root   /www/;
            index  index.html index.htm;
        }
    }
 
然后,创建/www/文件,并创建index.html文件
[root@localhost ~]# mkdir /www/
[root@localhost ~]# vim  /www//index.html 
<h1>team<h1>
I am fine.
what are you dong?

测试访问https://www.,测试结果如下:

高性能的web服务器nginx_nginx简介   nginx_07

 

至此,nginx作为web服务器的配置已经完成了!!!