一、Nginx简介

Nginx是一款轻量级Web 服务器/反向代理服务器电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。由俄罗斯的程序设计师Igor Sysoev所开发,供俄国大型的入口网站及搜索引擎Rambler使用。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:新浪、网易、 腾讯等。

Nginx 可以在大多数 Unix like OS 上编译运行,并有 Windows 移植版,Nginx具有着众多优点。

1)Nginx 是一个很强大的高性能Web和反向代理服务器,它具有很多非常优越的特性;

2)Nginx 作为负载均衡服务器:Nginx 既可以在内部直接支持 Rails 和 PHP 程序对外进行服务,也可以支持作为 HTTP代理服务器对外进行服务;

3)Nginx 同时也是一个非常优秀的邮件代理服务器;

4)Nginx 采用C进行编写,不论是系统资源开销还是CPU使用效率都比 Perlbal 要好很多。

5)Nginx 是一个安装非常的简单,配置文件非常简洁(还能够支持perl语法),Bugs非常少的服务器:Nginx 启动特别容易,并且能够平滑升级。

2013年最新统计Nginx 在Web Server市场中所占的市场份额

093725263.jpg

二、Nginx 的基本HTTP服务器特性

1、处理静态文件,索引文件以及自动索引;打开文件描述符缓存;

2、使用缓存加速反向代理,简单负载均衡以及容错;

3、远程FastCGI,uwsgi,SCGI,和memcached服务的缓存加速支持;

4、模块化的架构,过滤器包括gzip压缩、ranges支持、chunked响应、XSLT,SSI以及图像缩放。在SSI 过滤器中,一个包含多个SSI的页面,如果经由FastCGI或反向代理处理,可被并行处理;

5、支持SSL,TLS SNI。

三、Nginx 常用的其他HTTP服务器的特性

1)基于名字和IP的虚拟主机;

2)Keep-alive和pipelined连接支持;

3)重新加载配置以及在线升级时,不需要中断正在处理的请求;

4)自定义访问日志格式,带缓存的日志写操作以及快速日志轮转;

5)3xx-5xx错误代码重定向;

6)重写(rewrite)模块:使用正则表达式改变URI;

7)基于客户端IP地址和HTTP基本认证机制的访问控制;

8)来自同一地址的同时连接数或请求数限制,速度限制。

四、Nginx 常用的架构和扩展性

1)一个进程和多个工作进程;

2)支持事件机制;

3)支持AIO;

4)支持sendfile;

5)支持Accept-fileters.

五、Nginx 的进程工作

Nginx会按需同时运行多个进程:一个主进程(master)和几个工作进程(worker),配置了缓存时还会有缓存加载器进程(cache loader)和缓存管理器进程(cache manager)等。所有进程均是仅含有一个线程,并主要通过“共享内存”的机制实现进程间通信。

1、主进程主要完成如下工作,主进程以root用户身份运行:

1) 读取并验正配置信息;

2) 创建、绑定及关闭套接字;

3) 启动、终止及维护worker进程的个数;

4) 无须中止服务而重新配置工作特性;

5) 控制非中断式程序升级,启用新的二进制程序并在需要时回滚至老版本;

6) 重新打开日志文件,实现日志滚动;

7) 编译嵌入式perl脚本。

2、worker进程主要完成的任务包括:

1) 接收、传入并处理来自客户端的连接;

2) 提供反向代理及过滤功能;

3) nginx任何能完成的其它任务。

3、cache loader进程主要完成的任务包括:

1) 检查缓存存储中的缓存对象;

2) 使用缓存元数据建立内存数据库。

4、cache manager进程的主要任务是检查缓存的失效及过期检验;

六、Nginx的编译安装

1、下载nginx源码包,并将其解压;

[root@zly ~]# lftp 172.16.0.1
lftp 172.16.0.1:~> cd pub/Sources/sources/nginx/
lftp 172.16.0.1:/pub/Sources/sources/nginx> ls
-rwxr--r--    1 500      500        767688 Sep 13 01:49 nginx-1.4.2.tar.gz
-rwxr--r--    1 500      500       1415582 Sep 13 08:35 tengine-1.4.6.tar.gz
-rwxr--r--    1 500      500       1437781 Sep 13 08:35 tengine-1.5.1.tar.gz
lftp 172.16.0.1:/pub/Sources/sources/nginx> get nginx-1.4.2.tar.gz
767688 bytes transferred                          
lftp 172.16.0.1:/pub/Sources/sources/nginx> bye
[root@zly ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.4.2.tar.gz
[root@zly ~]# tar xf nginx-1.4.2.tar.gz
[root@zly ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.4.2  nginx-1.4.2.tar.gz

2、解决编译安装时所依赖的关系;

[root@zly ~]#  yum groupinstall "Development Tools" "Server Platform Deveopment"
[root@zly ~]# yum -y install openssl-devel pcre-devel
Loaded plugins: fastestmirror, refresh-packagekit, security
Loading mirror speeds from cached hostfile
..........
Installed:
  pcre-devel.x86_64 0:7.8-6.el6                                                                 
Complete!

3、添加nginx用户,并以之运行nginx服务;

[root@zly ~]# groupadd -r nginx
[root@zly ~]# useradd -r -g nginx nginx
[root@zly ~]# id nginx
uid=496(nginx) gid=493(nginx) groups=493(nginx)


4、编译安装nginx;

[root@zly nginx-1.4.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
[root@zly nginx-1.4.2]# make && make install

5、为nginx服务提供Sysv init服务脚本

[root@zly nginx-1.4.2]# 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


6、将nginx加入服务列表中,并启动nginx服务;

[root@zly nginx-1.4.2]# vim /etc/rc.d/init.d/nginx
[root@zly nginx-1.4.2]# chmod +x /etc/rc.d/init.d/nginx
[root@zly nginx-1.4.2]# chkconfig --add nginx
[root@zly nginx-1.4.2]# chkconfig nginx on
[root@zly nginx-1.4.2]# chkconfig --list nginx
nginx           0:off   1:off   2:on    3:on    4:on    5:on    6:off
[root@zly nginx-1.4.2]# service nginx start
Starting nginx:                                            [  OK  ]


7、测试nginx服务,访问相关http页面。

165554343.jpg

七、Nginx的配置文件

/etc/nginx/nginx.conf

1、主要分两段:全局配置段和http配置段

2、全局配置段:主要有user段和worker段

* 全局配置段示例

#user  nobody;
worker_processes  1;
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
    worker_connections  1024;
}

3、http配置段:http上下文四件套

http --> server --> location --> if

* http配置段示例

http {
    include       mime.types;
    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;
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #gzip  on;
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
            root   html;
            index  index.html index.htm;
        }
        #error_page  404              /404.html;
 }


4、HTTPS server段

# HTTPS server
    #
    #server {
    #    listen       443;
    #    server_name  localhost;
    #    ssl                  on;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
    #    ssl_session_timeout  5m;
    #    ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers   on;
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


八、Nginx配置文件应用示例

Nginx 官方配置文档http://nginx.org/en/

1、全局配置段在核心模块 Core functionality模块上http://nginx.org/en/docs/ngx_core_module.html

211553328.jpg

2、http配置段在 HTTP Core模块。

211609325.jpg

3、server配置段在 HTTP Core模块下的 server模块。

211631704.jpg

4、location配置段在 HTTP Core模块下的 location模块。

211647405.jpg

5、实现服务访问控制的配置在 Access模块与Auth Basic模块。

1)*实现基于虚拟主机ip的访问控制

[root@ zly ~]# vim /etc/nginx/nginx.conf
worker_processes  2;
........
events {
    worker_connections  1024;
}
........
 sendfile        on;
........
 keepalive_timeout  5;
........
    server {
        listen      172.16.20.1:80;
        server_name  localhost;
        root /web/vhost1;
        location / {
            root   /web/vhost1;
            index index.html;
                   } 
         } 
    server {
        listen      172.16.20.3:80;
        server_name  xiaozheng;
        root /web/vhost2;
[root@ zly ~]# mkdir -pv /web/{vhost1,vhost2}
mkdir: created directory `/web'
mkdir: created directory `/web/vhost1'
mkdir: created directory `/web/vhost2'
[root@ zly ~]# vim /web/vhost1/index.html
<h1>Welcom to zly Host1</h1>
[root@ zly ~]# vim /web/vhost2/index.html
<h1> Welcom to new Host2</h1>
[root@ zly ~]# ifconfig eth0:1 172.16.20.3 up
[root@ zly ~]# ifconfig
eth0:1    Link encap:Ethernet  HWaddr 00:0C:29:38:7F:85
          inet addr:172.16.20.3  Bcast:172.16.255.255  Mask:255.255.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
[root@ zly ~]# service nginx restart
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Stopping nginx:                                            [  OK  ]
Starting nginx:                                            [  OK  ]
[root@ zly ~]# ss -tanlp | grep nginx
LISTEN     0      128             172.16.20.3:80                       *:*      users:(("nginx",2628,7),("nginx",2629,7),("nginx",2630,7))
LISTEN     0      128             172.16.20.1:80                       *:*      users:(("nginx",2628,6),("nginx",2629,6),("nginx",2630,6))

访问nginx页面

215908146.jpg

215908398.jpg

注:同理基于虚拟主机名或虚拟主机端口,只需要在两个server配置段定义不同的主机名或不同的虚拟主机端口

2)*实现nginx服务的Auth Basic访问控制

[root@ zly ~]# useradd zly
[root@ zly ~]# useradd xiaozheng
[root@ zly ~]# htpasswd -c -m /etc/nginx/.htpasswd zly
New password:
Re-type new password:
Adding password for user zly
[root@ zly ~]# htpasswd -c -m /etc/nginx/.htpasswd xiaozheng
New password:
Re-type new password:
Adding password for user xiaozheng
[root@ zly ~]# vim /etc/nginx/nginx.conf      
    server {
        listen      172.16.20.1:80;
        server_name  localhost;
        root /web/vhost1;
        auth_basic "Restricted Area";
        auth_basic_user_file /etc/nginx/.htpasswd;
        location / {
            root   /web/vhost1;
            index index.html;
                    }
            }
[root@ zly ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@ zly ~]# service nginx reload
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Reloading nginx:                                           [  OK  ]

222343795.jpg

6、实现自动索引文件 Auto Index模块。

7、自定义响应报文首部配置在 Headers模块上。

8、实现uri重写的配置在Rewrite模块上。