Nginx:是一款轻量级的web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,是Apache服务器不错的替代品,能够支持高达 50,000 个并发连接数的响应。

      Nginx的编译安装:

     1:创建普通用户和组,Nginx

# groupadd -r nginx
# useradd -g nginx -r -s /sbin/nologin -M nginx

  解决依赖关系安装pcre-devel

# yum -y install pcre-devel

    解压   nginx-1.4.7.tar.gz 并编译安装

# tar -xf nginx-1.4.7.tar.gz
# cd nginx-1.4.7
# ./configure
# make && make install

wKiom1NbaSjQT1P8AAPoVWbMoF0381.jpg

  编译安装后Nginx的相关目录

  给Nginx提供一个启动脚本

# vim/etc/rc.d/init.d/nginx


#!/bin/sh
#
# nginx - this script starts and stops the nginx daemin
#
# chkconfig:   - 85 15
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /usr/local/nginx/conf/nginx.conf
# pidfile:     /usr/local/nginx/logs/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/local/nginx/sbin/nginx"
prog=$(basename $nginx)
NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
lockfile=/var/lock/subsys/nginx
start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    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
    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

   给脚本一个执行权限

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

   添加至服务管理列表,并让其开机自动启动:

# chkconfig --add nginx
# chkconfig nginx on

   启动服务

# service nginx start

   查看nginx进程

# ps -aux | grep nginx

wKiom1NbgBTzBFq8AANC6TDdyvE238.jpg

  Nginx的配置可以分为三部分:

  1:Nginx的核心配置段

  2:Nginx的http配置段

  3:Nginx的mail配置段

  在核心配置段主要配置如图所示的内容:>

  user:------>定义了运行worker进程的用户和组

  worker_processes:------>定义了开启worker进程的个数,默认为1

  #error_log:------>错误日子的路劲和级别

  pid:------>pid文件的路径

  worker_connections:------>每个worker进程的最大并发连接数

  http段配置

  http {

  sendfile:------>是否启用sendfile功能

  keepalive_timeout:------>持连接的超时时间

  server {

  listen       80;------>监听端口

  server_name  localhost;------>设定主机名


  location / {

           root   html;------>定义网页存放位置

           index  index.html index.htm;------>提供的默认网页

       }

}


}

   server{}主要是配置虚拟主机,server_name 可以跟多个,空格隔开,分号结尾。

   location{}对URL做模式匹配,对匹配到的URL请求访问做出的处理机制。

   格式:location [ = | ~ | ~* | ^~ ] uri { ... }
       location@name { ... }

        =:精确匹配

        ~:正则表达式模式匹配,匹配时区分字符大小写

        ~*:正则表达式模式匹配,匹配时忽略字符大小写

        ^~:URI的前半部分匹配,不检查正则表达式

   其余别的配置选项我们在实现各种功能的时候在一一介绍:


   一:Nginx的反向代理功能:Nginx通过proxy模块实现反向代理,在实现反向代理功能时的最重要指令为proxy_pass,它能够将location定义的某URI代理至指定的服务器上,简单示例:

server {
    listen 80;
    server_name www.a.com;
    location / {
    proxy_pass http://192.168.2.110;
}
}

   我们对根的请求都代理到后端192.168.2.110服务器上。

   做路径映射的时候proxy_pass的代理地址写法:proxy_pass http://192,168,2,110/


server {
    listen 80;
    server_name www.a.com;
    location /aaa {
    proxy_pass http://192.168.2.110/;
}
}

   我们定义192.168.2.110的Documentroot是 /var/www/html 页面文件是/var/www/html/index.html,如果110后面没有斜线,就相当于我们访问的是192.168.2.110服务器上/var/www/html/aaa目录下的index.html文件,如果有斜线,就是把www.a.com/aaa 映射为192.168.2.110上/var/www/html/index.html。

   简单说几个代理常用的模块指令

proxy_connect_timeout  等待用户连接请求的最大时长。
proxy_hide_header 隐藏响应首部的设定
proxy_pass_header 显示相应首部的设定
proxy_set_header 重新定义nginx发送到upstream server的请求报文首部,可以将用户的真实ip添加进请求报文首部,结合http的日志,方便以后做数据分析。

  演示添加客户IP到请求报文首部,结合httpd的日志文件做分析的操作:

  编辑配置nginx的配置文件

server {
       listen         80;
       server_name    www.a.com;
       location /aaa {
           proxy_pass http://192.168.2.110;
           proxy_set_header Y-REAL-IP $remote_addr;
       }
       }

  Y-REAL-IP是自己起名定义的,

  $remote_addr:客户端ip Nginx的内置变量

  我们可以先抓包看看在apache服务器端

# tcpdump -i eth1 -nn -X tcp port 80

wKiom1Nce1bjD1zJAAEzNWWH1-Q654.jpg

wKioL1NceyzSHPyJAAC6yTsXZwk236.jpg

   修改apache服务器的日志格式%h为{Y-REAL-IP}i

wKioL1NcfK_icOcCAACz2nAsa1s718.jpg

   访问查看日志:

# tail -f /var/log/httpd/access_log

wKiom1NcfYaSrbnUAAJ0vZBWV74067.jpg

  如要让客户端知道是谁代理的可以使用add_header 指令

server {
        listen         80;
        server_name    www.a.com;
        add_header X-VIA $server_addr;
        location / {
            proxy_pass http://webserver/;
            proxy_set_header Y-REAL-IP $remote_addr;
        }
        }

wKioL1Nc2JaDPfFPAAK6yro2EKw247.jpg

 二:Nginx的多服务器代理:要使用upstream的模块,此模块只能用在http上下文中。格式:

syntax: upstream name { ... }
default:     —
context:    http

   server的使用格式:

syntax: server address [parameters];
default:     —
context:    upstream

   常用的parameters:

  1:weight=number ---设定权重

  2:max_fails=number---最大败尝试次数

  3:fail_timeout=time---失败尝试超时时长

  4:backup---定义所代理的服务器全部宕机时提供临时页面的服务器

  5:down---手动指定那个上游服务器下线。

  配置upstream:

upstream webserver {      
        server 192.168.2.110;
        server 192.168.2.114;
        server localhost backup;
        }

  需要注意的是:在upstream定义server的时候直接写ip或者主机名,不要使用协议,例如:

server http://192.168.2.100;

   这是错误的写法,因为我们在proxy_pass中引用upstream定义的祖名webserver的时候会使用协议。

server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        }

  这样多服务器代理就配置OK,并且实现了负载均衡,当两台主机全部宕掉会从本地提供一个临时页面。

   upstream常用到的两个模块指令:

   server:定义组

   ip_hash 相当于ipvs的sha算法 定义在upstream中做源地址绑定

   least_conn 根据最少连接数做调度。

   health_check;做健康状态检测,但是好多功能在1.4.7的版本还不支持。

   二者不可同时使用

upstream webserver {      
        server 192.168.2.110;
        server 192.168.2.114;
        server 127.0.0.1 backup;
        ip_hash;
        }

upstream webserver {      
        server 192.168.2.110;
        server 192.168.2.114;
        server 127.0.0.1 backup;
        least_conn;
        }

   三:代理缓存功能:

   首先需要设定缓存区,用到的三个指令:

   1: proxy_buffer_size size  设定用于暂存来自于upstream服务器的第一个响应报文的缓冲区大小

   2: proxy_buffering on|off  是否启用缓存与proxy_max_temp_file_size结合使用,启用proxy_buffering并将proxy_max_temp_file_size设定为0能够启用缓存响应报文的功能,并能够避免将其缓存至磁盘中;

   3:proxy_buffers n nk 用于设置来自upstream服务器的响应报文的缓冲区大小;几个缓存区

   Nginx的缓存机制:将来自upstream的响应缓存至本地,并在后续的客户端请求同样内容时直接从本地构造响应报文,不使用内存做缓存,而是使用磁盘 但是会把缓存定义到可以使用内存做缓存的服务器上, Nginx是在磁盘上做数据缓存,在内存中做数据的索引hash表,

   定义缓存的指令:

proxy_cache_pathpath [levels=levels] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time];

   定义缓存数据的磁盘位置,索引名称及其索引区域空间大小。只能定义在http的上下文,可用参数:

   1:levels:每级子目录名称的长度,有效值为1或2,每级之间使用冒号分隔,最多为3级。

   2:inactive:已缓存但不常被访问的缓存对象,缓存多久就会被删除。

   3:max_size:磁盘缓存空间大小的上限。

   4:loader_files:一次可以加载多少个缓存到内存

   5:loader_sleep:缓存加载器每次迭代工作之后的睡眠时长

   6:loader_threashold:缓存加载器的最大睡眠时长

   7:proxy_cache_use_stale error | timeout | invalid_header | updating | http_500|

   8:http_502 | http_503 | http_504 | http_404 | off  

   无法联系到upstream服务器时的哪种情形下让nginx使用本地缓存的过期的缓存对象直接响应客户端请求

   9:proxy_cache_valid [ code ...]time

   用于为不同的响应设定不同时长的有效缓存时长

   10:proxy_cache_methods [GET HEAD POST]:

   为哪些请求方法启用缓存功能

   11:proxy_cache_bypass string:

   在哪种情形下,nginx将不从缓存中取数据  

   示例:

http{
    proxy_cache_path /web/nginx/cache levels=1:2 keys_zone=Ngincache:10m inactive=24h max_size=2g;
    server {
        listen         80;
        server_name    www.a.com;
        add_header X-VIA $server_addr;
        add_header X-Cache $upstream_cache_status;
        location / {
            proxy_pass http://webserver/;
            proxy_set_header Y-REAL-IP $remote_addr;
            proxy_cache         Ngincache;
            proxy_cache_valid 200 10m;
            proxy_cache_methods GET HEAD;
        }
        }
}

wKioL1NdFWbwfGYQAAOWRsh0mkA203.jpg

  可以看到我们的缓存命中。

  四:Nginx基于FastCGI与PHP-fpm服务器工作

location ~ \.php$ {
            root           a.com;
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;
            fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            include        fastcgi_params;

   注意fasrcgi_params的格式需要改动下,让Nginx的变量能让PHP读懂。


fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;

fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  QUERY_STRING       $query_string;

fastcgi_param  REQUEST_METHOD     $request_method;

fastcgi_param  CONTENT_TYPE       $content_type;

fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;

fastcgi_param  REQUEST_URI        $request_uri;

fastcgi_param  DOCUMENT_URI       $document_uri;

fastcgi_param  DOCUMENT_ROOT      $document_root;

fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  REMOTE_ADDR        $remote_addr;

fastcgi_param  REMOTE_PORT        $remote_port;

fastcgi_param  SERVER_ADDR        $server_addr;

fastcgi_param  SERVER_PORT        $server_port;

fastcgi_param  SERVER_NAME        $server_name;

   这样我们就可以访问到php页面了。实现了简单的对php的请求代理。