nginx:2、ngnix安装及配置详解

前言

一、Nginx 安装

二、Nginx 配置文件

   1、nginx主配置文件

   2、nginx主配置文件结构

   3、nginx的配置和优化详解

   4、http核心模块的内置变量

三、nginx模块

   1、配置Nginx的虚拟主机

   2、配置Nginx的用户认证

   3、配置Nginx下载站

   4、防盗链

   5、url 重写

   6、配置Nginx提供状态页面

  7、if语句


一、前言

     在上一篇博文中我们讲解了I/O模型、Web服务器的工作原理及Nginx的基本特性,我们知道Nginx有两个基本功能,一个是作为Web服务器(在这篇博文中重点讲解),另一个是作为反向代理(在后面的博文中详细讲解)。


二、Nginx 安装

注,测试环境 CentOS6.5-x86_64 , Nginx 1.4.7

1、安装依赖包

[root@BAIYU_179 ~]# yum -y install openssl-devel pcre-devel

2、添加系统用户nginx,实现以之运行nginx服务进程

# useradd -r  nginx

3、安装nginx

[root@BAIYU_179 ~]# ls
anaconda-ks.cfg  install.log  install.log.syslog  nginx-1.4.7.tar.gz  trash.sh
[root@BAIYU_179 ~]# tar xf nginx-1.4.7.tar.gz 
[root@BAIYU_179 ~]# cd nginx-1.4.7
[root@BAIYU_179 nginx-1.4.7]# ls
auto  CHANGES  CHANGES.ru  conf  configure  contrib  html  LICENSE  man  READ
# ./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
  # make && make install

4、启动nginx

启动nginx前先检查是否有错误再启动

[root@BAIYU_179 nginx-1.4.7]# nginx -h
nginx version: nginx/1.4.7
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file
[root@BAIYU_179 nginx]# nginx -t          
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: [emerg] mkdir() "/var/tmp/nginx/client/" failed (2: No such file or directory)
nginx: configuration file /etc/nginx/nginx.conf test failed
[root@BAIYU_179 nginx]# nginx -t          
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: [emerg] mkdir() "/var/tmp/nginx/client/" failed (2: No such file or directory)
nginx: configuration file /etc/nginx/nginx.conf test failed
[root@BAIYU_179 nginx]# ^C
[root@BAIYU_179 nginx]# ls /var/tmp/n
ls: 无法访问/var/tmp/n: 没有那个文件或目录
[root@BAIYU_179 nginx]# mkdir -pv /var/tmp/nginx/client
mkdir: 已创建目录 "/var/tmp/nginx"
mkdir: 已创建目录 "/var/tmp/nginx/client"
[root@BAIYU_179 nginx]# nginx -t                       
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@BAIYU_179 nginx]# nginx 
[root@BAIYU_179 nginx]# netstat -nlptu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      28946/nginx         
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1366/sshd           
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1173/master

wKiom1Y_RjvAj_AgAACNIwV0J5o781.png

5、为nginx提供SysV init脚本

[root@BAIYU_179 init.d]# vi 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 init.d]# ls
auditd            halt       lvm2-lvmetad  netconsole  ntpd     rdisc        saslauthd  udev-post
blk-availability  ip6tables  lvm2-monitor  netfs       ntpdate  restorecond  single
crond             iptables   messagebus    network     oddjobd  rsyslog      sshd
functions         killall    mysqld        nginx       postfix  sandbox      svnserve
[root@localhost init.d]# chmod +x nginx 
[root@localhost init.d]# ls
auditd            halt       lvm2-lvmetad  netconsole  ntpd     rdisc        saslauthd  udev-post
blk-availability  ip6tables  lvm2-monitor  netfs       ntpdate  restorecond  single
crond             iptables   messagebus    network     oddjobd  rsyslog      sshd
functions         killall    mysqld        nginx       postfix  sandbox      svnserve
[root@localhost init.d]# chkconfig --add nginx
[root@localhost init.d]# chkconfig --list nginx
nginx           0:off   1:off   2:off   3:off   4:off   5:off   6:off
[root@localhost init.d]# 
[root@localhost init.d]# service nginx status
nginx (pid 4147 4146) is running...
[root@localhost init.d]# service nginx sysconfigtest
Usage: /etc/init.d/nginx {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}
[root@localhost init.d]# service nginx configtest   
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost init.d]# 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  ]

三、Nginx配置

1、查看nginx 主配置文件/etc/nginx/nginx.conf文件

[root@localhost nginx]# cat nginx.conf

#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;
}


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;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #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;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

2、nginx 主配置文件/etc/nginx/nginx.conf结构

Nginx的配置文件/etc/nginx/nginx.conf分为2段:

1)main配置段

main段中又包括events段

2)http{


}

http段中包括:server段(主机设置)、

server段中包括:upstream(负载均衡服务器设置)和 location(URL匹配特定位置的设置)。

这个段通常也被称为nginx的上下文,每个段的定义格式如下所示。

<section> {

<directive> <parameters>;

}

需要注意的是,其每一个指令都必须使用分号(;)结束,否则为语法错误

语法格式:

参数名 值1 [值2...];

支持使用变量:

    模块内置变量

    用户自定义变量

格式:set var_name value

main段设置的指令将影响其他所有设置;

server段的指令主要用于主机设置;

upstream指令主要用于负载均衡,设置一系列的后端服务器;

location部分用于匹配url

这四者之间的关系如下:

n3

     在这4个部分当中,每个部分都包含若干指令,这些指令主要包含Nginx的主模块指令、事件模块指令、HTTP核心模块指令。同时每个部分还可以使用其他HTTP模块指令,例如Http SSL模块、Http Gzip Static模块和Http Addition模块等。

3、配置文件/etc/nginx/nginx.conf详解

 1)正常运行的必备配置:

#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;
worker_rlimit_nofile 65535; 
events {
    use epoll;
    worker_connections  1024;  
}

    1.user username [groupname];

              以那个用户身份运行,编译安装时指定了用户,如果想改变在这里定义就可以

    2.pid /path/to/pid_filename;    

             指定nginx的pid文件

    3.worker_rlimit_nofile #;

               指定一个worker进程所能够打开的句柄数(就是文件的个数?)

    4.worker_rlimit_sigpending #;

               设定每个用户能够发往worker进程的信号的数量;

  2)优化性能相关的配置

    1.worker_procrsses #;

                work进程的个数 ,通常其数值应该为cpu的物理核心数减1

(注,如果负载以CPU密集型应用为主,如SSL或压缩应用,则worker数应与CPU数相同;

如果负载以IO密集型为主,如响应大量内容给客户端,则worker数应该为CPU个数的1.5或2倍。)

    2.worker_cpu_affinity CPUMASK ....;     #cpu亲缘性

           0000  #cpu掩码,如果4个cpu核心则用0000表示,从右到左依次对应第1个...第4个cpu核心

           0001  #第1个cpu核心

           0010  #第2个

           0100

           1000

        对应位上使用cpu,要做单独绑定,例如:

          work_procrsses 6  #保证了这6个进程依次在这6个cpu上运行,不会切换,但这些cpu可能会运行别的进程

          worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000

    3.ssl_engine DEVICE;

               在存在ssl硬件加速器的服务器上,指定所使用的ssl硬件加速设备

    4.timer_resolution t; 

               每次内核事件调用返回时,都会使用gettimeday()来更新nginx缓存时钟;timer_resolution用于定义每隔多久才会由gettimeday()更新一次缓存时钟;x86-64系统上,gettimeday()代价已经很小,可以忽略此配置

    5.worker_priority nice;

                -20到19之间的值,值越小越优先调用

 3)跟事件相关的配置

    1.accept_mutex [on|off];

                是否打开nginx的负载均衡锁;此锁能够让多个worker进行轮流地、序列化地与新的客户端建立连接;而通常当一个worker进程的负载达到其上限的7/8,master就尽可能不将请求调度至worker

    2.lock_file /path/to/lock_file;

                锁文件

    3.accept_mutex_delay #ms;

                使用accept锁以后,一个用户请求,同时只有一个worker能取得锁,一个worker进程为取得accept锁的等待时长,即用户建立等待的时间,如果某worker进程在某次试图取得锁时失败了(其它进程正在使用),至少要等待#ms才能再一次请求锁

    4.multi_accept on|off;

                是否允许一次性地响应多个用户请求,默认为off

    5.use [epoll|rtsig|select|poll];  #关键

                指定使用哪种事件模型,建议让nginx自动选择(就是不用在配置文件中添加还是通过哪种方式让它自动选择?)

    6.worker_connections #;

                每个worker能够并发响应的最大请求数,如果为代理服务器的话,                                 worker_rlimit_nofile=worker_commections*2

 4)用于调试、定位问题:只在调试nginx时使用

1.daemon [on|off];

               关闭提供守护进程的模式,是否让nignx运行于后台;调试时应该为off,使得所有信息直接输出在控制台,默认为on

2.master_process on|off;

               是否以master/worker模式运行nginx,默认为on,调试时可以设置为off以方便追踪

3.error_log /path/to/error_log LEVEL;

               错误日志文件及其级别,调试时可以使用debug级别,但要求在编译时必须使用--with-debug启用debug功能,默认通常为error级别

(日志输出级别有debug、info、notice、warn、error、crit可供选择,其中,debug输出日志最为最详细,而crit输出日志最少)

 5)nginx的http web功能

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;

下面详细介绍这段代码中每个配置选项的含义:

  • include是个主模块指令,实现对配置文件所包含的文件的设定,可以减少主配置文件的复杂度。类似于Apache中的include方法。

  • default_type属于HTTP核心模块指令,这里设定默认类型为二进制流,也就是当文件类型未定义时使用这种方式,例如在没有配置PHP环境时,Nginx是不于解析的,此时,用浏览器访问PHP文件就会出现下载窗口。

  • log_format是Nginx的HttpLog模块指令,用于指定Nginx日志的输出格式。main为此日志输出格式的名称,可以在下面的access_log指令中引用。

  • client_max_body_size用来设置允许客户端请求的最大的单个文件字节数。

  • client_header_buffer_size用于指定来自客户端请求头的headerbuffer大小。对于大多数请求,1KB的缓冲区大小已经足够,如果自定义了消息头或有更大的cookie,可以增加缓冲区大小。这里设置为32KB。

  • large_client_header_buffers用来指定客户端请求中较大的消息头的缓存最大数量和大小, “4”为个数,“128K”为大小,最大缓存为4个128KB。

  • sendfile参数用于开启高效文件传输模式。

  • 当使用sendfile函数时,tcp_nopush才起作用,它和指令tcp_nodelay是互斥的。tcp_corklinuxtcp/ip传输的一个标准了,这个标准的大概的意思是,一般情况下,在tcp交互的过程中,当应用程序接收到数据包后马上传送出去,不等待,而tcp_cork选项是数据包不会马上传送出去,等到数据包最大时,一次性的传输出去,这样有助于解决网络堵塞,已经是默认了。

  • 也就是说tcp_nopush = on 会设置调用tcp_cork方法,结果就是数据包不会马上传送出去,等到数据包最大时,一次性的传输出去,这样有助于解决网络堵塞。

  • keepalive_timeout用于设置客户端连接保持活动的超时时间。在超过这个时间之后,服务器会关闭该连接。

  • client_header_timeout用于设置客户端请求头读取超时时间。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误。

  • client_body_timeout用于设置客户端请求主体读取超时时间,默认值为60。如果超过这个时间,客户端还没有发送任何数据,Nginx将返回“Request time out(408)”错误。

  • send_timeout用于指定响应客户端的超时时间。这个超时仅限于两个连接活动之间的时间,如果超过这个时间,客户端没有任何活动,Nginx将会关闭连接。

  • gzip用于设置开启或者关闭gzip模块,“gzip on”表示开启gzip压缩,实时压缩输出数据流。

Http_Gzip模块配置

下面配置Nginx的HttpGzip模块。这个模块支持在线实时压缩输出数据流。要查看是否安装了此模块,需要使用下面的命令:

[root@localhost nginx]# nginx -?
nginx version: lighttpd/1.4.37
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
  -?,-h         : this help
  -v            : show version and exit
  -V            : show version and configure options then exit
  -t            : test configuration and exit
  -q            : suppress non-error messages during configuration testing
  -s signal     : send signal to a master process: stop, quit, reopen, reload
  -p prefix     : set prefix path (default: /usr/)
  -c filename   : set configuration file (default: /etc/nginx/nginx.conf)
  -g directives : set global directives out of configuration file

[root@localhost nginx]# nginx -V
nginx version: lighttpd/1.4.37
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC) 
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --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 --with-http_realip_module

通过nginx -V 命令可以查看安装Nginx时的编译选项。由输出可知,我们已经安装了HttpGzip模块。下面是HttpGzip模块在Nginx配置中的相关属性设置:

#gzip  on;
#gzip_disable "msie6";
#gzip_min_length  1k;
#gzip_buffers     4  16k;
#gzip_http_version  1.1;
#gzip_proxied any;
#gzip_comp_level  2;
#gzip_types  text/plain application/x-javascript text/css application/xml;
#gzip_vary  on;

http {
	gzip on;
	gzip_http_version 1.0;
	gzip_comp_level 2;
	gzip_types text/plain text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript application/json;
	gzip_disable msie6;
}
  • gzip用于设置开启或者关闭gzip模块,“gzip on”表示开启gzip压缩,实时压缩输出数据流。

  •  gzip_disable 不压缩的类型或浏览器

  • gzip_min_length用于设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取。默认值是0,不管页面多大都进行压缩。建议设置成大于1K的字节数,小于1K可能会越压越大。

  • gzip_buffers表示申请4个单位为16K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。

  • 其中的gzip_http_version的设置,它的默认值是1.1,就是说对HTTP/1.1协议的请求才会进行gzip压缩
    如果我们使用了proxy_pass进行反向代理,那么nginx和后端的upstream server之间是用HTTP/1.0协议通信的。

  • gzip_proxied
    Nginx做为反向代理的时候启用,
    param:off|expired|no-cache|no-sotre|private|no_last_modified|no_etag|auth|any]
    expample:gzip_proxied no-cache;
    off �C 关闭所有的代理结果数据压缩
    expired �C 启用压缩,如果header中包含”Expires”头信息
    no-cache �C 启用压缩,如果header中包含”Cache-Control:no-cache”头信息
    no-store �C 启用压缩,如果header中包含”Cache-Control:no-store”头信息
    private �C 启用压缩,如果header中包含”Cache-Control:private”头信息
    no_last_modified �C 启用压缩,如果header中包含”Last_Modified”头信息
    no_etag �C 启用压缩,如果header中包含“ETag”头信息
    auth �C 启用压缩,如果header中包含“Authorization”头信息
    any �C 无条件压缩所有结果数据

  • gzip_comp_level用来指定gzip压缩比,1 压缩比最小,处理速度最快;9 压缩比最大,传输速度快,但处理最慢,也比较消耗CPU资源。

  • gzip_types用来指定压缩的类型,无论是否指定,“text/html”类型总是会被压缩的。

  • gzip_vary选项可以让前端的缓存服务器缓存经过gzip压缩的页面,例如,用Squid缓存经过Nginx压缩的数据。

6)server段

server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;

nginx必须使用虚拟机来配置站点:每个虚拟主机使用一个server{}段来配置

server{


}

非虚拟主机的配置和公共选项,需要定义在server之外,http之内

http{

directive value;

....

        server{

               location / {

                           }

}

server{


}

......

}


1.server{  }

 定义一个虚拟主机:nginx支持使用基于主机名或IP的虚拟主机

2.listen

  listen address[:port];

  listen prot;

  listen unix:socket;

  default_server:定义此server为http中默认的server;如果所有的server中没有任何一个listen使用此参数,那么第一个server即为默认server

  rcvbuf=SIZE:接收缓存大小

  sndbuf=SIZE: 发送缓存大小

  ssl:https server:必须以ssl连接

           各参数用空格分开

3.server_name [...];

Syntax:	server_name name ...;
Default:	
server_name "";
Context:	server
Sets names of a virtual server, for example:

server {
    server_name example.com www.example.com;
}

  server_name可以跟多个主机名,名称可以使用通配符和正则表达式(通常以~开头):当nginx收到一个请求时,会取出其首部的server的值,而后跟众server_name进行比较:比较方式

   (1) 先做精确匹配   www.magedu.com

   (2) 左侧通配符匹配  *.magedu.com

   (3) 右侧通配符匹配  www.*

   (4) 正则表达式匹配   #nginx配置文件中支持的是扩展正则表达式

4.server_name_hash_bucket_size 32|64|128;

  为了实现快速主机查找,nginx使用hash表来保存主机名

 location / {
            root   html;
            index  index.html index.htm;
        }

5.location [ =|~|~*|^~] uri {参数 ... };

  location @name { 参数... };

   功能:允许根据用户请求的URI来匹配指定的各location以进行访问配置;匹配到时,将被location块中的配置所处理

   =:精确匹配

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

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

   ^~:只需要前半部分与uri匹配即可,不检查正则表达式

   匹配优先级:

   "字符字面量最精确匹配"、正则表达式检索(由多个时,由第一个匹配到的所处理),

   文件路径定义

1.root PATH

设置web资源路径,用于指定请求的根文档目录,从根开始匹配

例如:location ^~ /images/ {

                root /web;

      }

可以匹配到http://www.magedu.com/images/b.html;但资源实际存放位置是/web/imges/

2.alias PATH

指定路径别名,只能用于location中,从最后一个/开始匹配

例如:location ^~ /images/ {

               alias /web;

      }

可以匹配到http://www.magedu.com/images/b.html;但资源实际存放位置是/web,url中用/images映射/web

3.index FILE ...;

        定义默认页面,可以跟多个值。自左向右匹配

4.error_page CODE ... [=[response]] uri;

当对于某个请求发回错误时,如果匹配上了error_page指令中设定的code,则从定向至新的新URI中;错误页面重定向

5.try_files path1 [path2...] uri;

自左向右尝试读取有path所指定路径,在第一找到即停止并返回,如果所有path均不存在,则返回最后一个uri

例如:location ~* ^/document/(.*)${

root /www/htdocs

try_files $uri /docu/$1 /temp.html

}

http://www.wangfeng7399.com/documents/a.html

http://www.wangfeng7399.com/docu/a.html

http://www.wangfeng7399.com/temp.html


    网络连接相关的设置

1.keepalive_timeout time;

保持连接的超时时长,默认为75s

2.keepalive_requests N;

在一次长连接上允许承载的最大请求数

3.keepalive_disable [msie6|safari |none];

对指定的浏览器禁止使用长连接

4.tcp_nodelay on|off

对keepalive连接是否使用tcp_nodelay选项

5.client_header_timeout time

读取http请求首部的超时时长

6.client_body_timeout time

读取http请求包体的超时时间

7.save_timeout time;

发送响应的超时时长


   对客户端请求的限制:

1.limit_except method ...{ ... }

   指定范围之外的其他方法的访问控制,只能用于location中

2.client_max_body_size SIZE;

    http请求包体的最大值,常用于限定客户端所能够请求的最大包体,根据请求首部中的Content-Length来检查,以避免无用的传输

3.limit_rate speed;

限制客户端每秒传输的字节数,默认为0,表示没有限制

4.limit_rate_after time;

nginx向客户端发送响应报文时,如果时长超过了此处指定的时长,则后续的发送过程开始限速


   文件操作的优化

1.sendfile on|off

是否启用sendfile功能

2.aio on|off

是否启用aio功能

3.open_file_cache max=N [incative=time]|off

是否打开文件缓存功能

max:用于缓存条目的最大值,允许打开的缓存条目最大数,当满两类以后将根据LRU(最小最少连接数)算法进行置换

inactive:某缓存条目在指定时长内没有被访问过时,将自动被删除;通常默认为60s

缓存的信息包括:

文件句柄、文件大小和上次修改时间

已经打开的目录结构:

没有找到或没有访问权限的信息

4.open_file_cache_errors on|off

是否缓存文件找不到或没有权限访问等相关信息

5.open_file_cache_valid time

多长时间检查一次缓存中的条目是否超出非活动时长,默认为60s

6.open_file_cache_min_use #

在inactive指定的时长内被访问超过此处指定的次数时,才不会被删除


    对客户端请求的特殊处理

1.ignore_invalid_headers on|off

是否忽略不合法的http首部,默认为on,off意味着请求首部中出现不合规的首部将拒绝响应,只能用于server和http

2.log_not_found on|off

用户访问的文件不存在时,是否将其记录到错误日志中

3.resolver address:

指定nginx使用的dns服务器地址

4.resolve timeout

指定DNS解析超时时长,默认为30s

5.server_tokens on|off

是否在错误页面中显示nginx的版本号


          跟内存及磁盘资源分配相关

1.client_body_in_file_only on|clean|off

http的包体存储在磁盘中,非off时表示存储,即时包体为0,也要存储在硬盘上;

如果为on,请求结束后包体文件不会被删除,clean表示删除,默认为off

2.client_body_in_single_buffer on|off

http的包体是否存储在内存buffer当中,默认为off

3.client_body_buffer_size size;

nginx接受http包体的内存缓存区大小

4.client_body_temp_path dir-path [level1[level2[level3]]]

定义http包体存放的临时目录,可以使用多级目录,level用来指定某一级目录的文件名的长度

client_body_temp_path /var/tmp/client 1 2

表示在/var/tmp/client创建16个一级子目录,在每个一级子目录创建256个二级子目录来存放缓存

5.client_header_buffer_size size

正常情况下接受用户请求的http报文header部分时分配的buffer大小,默认为1k

6.large_client_header_buffers number size

存储超大http请求首部的内存buffer大小及个数

7.connection_pool_size size

nginx对于每个建立成功的tcp连接都会预先分配一个内存池,此处机用于设定此内存池的初始大小,默认为256

8.request_pool_size size

nginx对于每个处理每个请求时会预先分配一个内存池,此处机用于设定此内存池的初始大小,默认为4K

4、http核心模块的内置变量:

$uri:当前请求的uri,不带参数

$request_uri:请求的uri,带完整参数

$host:http请求报文中host首部;如果请求中没有host首部,则以处理此请求的主机的主机名代替

$hostname:nginx服务运行所在主机的主机名

$remote_addr:客户端IP

$remote_port: 客户端port

$remote_user:使用用户认证时客户端用户输入的用户名

$request_filename:用户请求中的URI经过本地root或alias转换后映射的本地的文件路径

$request_method:请求方法

$server_addr:服务器地址

$server_name: 服务器名称

$server_port:服务器端口

$server_protocol:服务器向客户端发送响应时的协议,如http/1.1,http/1.0

$scheme:在请求中使用的scheme 映射协议本身的协议

$http_HEADER:匹配请求报文中指定的HEADER,$http_host匹配请求报文中的host首部

$sent_http_HEADER:匹配响应报文中指定的HERDER,例如$http_content_type匹配相应报文中的content-type首部

$document_root:当前请求映射到的root配置


四、nginx模块

配置使用nginx

1.nginx虚拟主机

1)、修改配置文件/etc/nginx/nginx.conf

    server {
        listen       80;
        server_name  www.a.com a.com;
        location / {
            root   /www/a.com/;
            index  index.html index.htm;
        }

        }

     server {
              listen 80;
              server_name www.b.org b.org;
              location / {
                           root /www/b.org/;
                           index index.html index.htm;
                         }
             }

2)创建测试页面

[root@localhost ~]# mkdir -pv /www/{a.com,b.org}
mkdir: created directory `/www'
mkdir: created directory `/www/a.com'
mkdir: created directory `/www/b.org'
[root@localhost ~]# vi /www/a.com/index.html
<h1>www.a.com</h1>
[root@localhost ~]# vi /www/b.org/index.html
<h1>www.b.org</h2>

3)修改测试机的hosts文件

Windows 7下路径:C:\Windows\System32\drivers\etc\hosts
增加两行:
192.168.100.10    www.a.com 
192.168.100.10    www.b.org

4)测试

wKioL1ZGuarh8C6eAABFiiW2wp4768.pngwKioL1ZGuanzWTYgAABGZmoB8r0736.png

2.访问控制access模块

和http2.4之前访问控制一样可以使用基于来源地址和用户认证两种方式来控制:

 1)基于来源地址访问控制

allow

deny

至上而下依次认证,默认为通过(上面允许了就有权限)

Example Configuration

location / {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}

 2)基于用户认证 

location /admin/ {             #/admin 对哪些路径进行用户认证

root

auth_basic "" 标题

auth_basic_user_file "" 密码的存放位置

}

使用htpasswd创建密码                 #要安装httpd

修改配置文件:

 server {
        listen       80;
        server_name  www.a.com a.com;
        location / {
            root   /www/a.com/;
            index  index.html index.htm;
            allow 192.168.100.0/24;
            deny all;
        }
         location /admin/ {
             root /www/a.com;
             auth_basic "admin area";
             auth_basic_user_file /etc/nginx/.htpasswd;
                          }

创建密码文件:

[root@localhost nginx]# yum install httpd -y
[root@localhost nginx]# htpasswd -c -m /etc/nginx/.htpasswd xj
New password: 
Re-type new password: 
Adding password for user xj
[root@localhost nginx]# htpasswd -m /etc/nginx/.htpasswd bengji
New password: 
Re-type new password: 
Adding password for user bengji
[root@localhost a.com]# mkdir admin
[root@localhost a.com]# vi admin/index.html
admin
admin
admin

测试:

wKioL1ZGwTCRTGuOAABriY6ucZY338.png

3、建立下载站点autoindex下载列表

Nginx默认是不允许列出整个目录的。如需此功能,打开nginx.conf文件,在location server 或 http段中加入autoindex on;另外两个参数最好也加上去,

  • autoindex_exact_size off;默认为on,显示出文件的确切大小,单位是bytes。改为off后,显示出文件的大概大小,单位是kB或者MB或者GB。

  • autoindex_localtime on;默认为off,显示的文件时间为GMT时间。改为on后,显示的文件时间为文件的服务器时间。

2.修改配置文件

location /download/{

root

autoindex on;

}

wKiom1ZGxcqCKoeMAABLGcbAYCo645.png

4.防盗链

(1)定义合规引用

  valid_referers none |block |server_names|string ...   

none:空,通过浏览器直接访问

block:请求报文中有referers字段但被清空

server_names:允许网站引用,

(2)判断不合规的引用

if ($invaild_referer) {

rewrite ^/.*$ http://www.a.com/403.html    #注意这里重写要使用绝对路径

}

5.URL rewrite

rewrite regex replacement [flag];

flag:标志位

last:一旦被当前规则匹配并重写后立即停止检查后续的其他rewrite的规则,而后通过重写后的规则重新发起请求

break:一旦被当前规则匹配并重写后立即停止检查后续的其他rewrite的规则,而后继续由nginx进行后续的操作

redirect:返回302临时重定向代码

permanent:返回301永久重定向

nginx最多循环10次,超出之后返回500错误

注意:一般将rewrite写在location中时都使用break标志,或者将rewrite写在if上下文中

rewrite_log on|off;

是否将重写过程记录在错误日志中,默认为notice级别;默认为off

return code:

用于结束rewrite规则,并且为客户返回状态码:可以使用的状态码有204,400,402-406,500-504等

Example:

server {
    ...
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  last;
    return  403;
    ...
}

案例:

1)配置/etc/nginx/nginx.conf文件

location /download/ {
         root /www/b.org/;
         rewrite ^/download/(.*\.(jpg|gif|jpeg|png))$ /images/$1 break;
                    }

2)在/www/b.org/目录下创建images目录并将一个图片放在这

[root@localhost b.org]# ls
1.png  download  index  index.html
[root@localhost b.org]# mkdir images
[root@localhost b.org]# mv ~/1.jpg /www/b.org/images/
[root@localhost b.org]# ls
download  images  index  index.html

wKiom1ZG16KhfAcEAARB2yz-fng491.png

可以看到访问的是url是/download/1.jpg,(download这个目录下是没有图片的)被重写至/images/1.jpg

现在再来看上面的防盗链设置:

在www.b.org中设置:只允许自己站点引用images目录下的图片,其它站点引用就返回433

location ~* \.(jpg|gif|jpeg|png)$ {
                                   root /www/b.org/;
                                   valid_referers none blocked www.b.org *.b.org;
                                   if ($invalid_referer) {
                                                  #return 433;
                                                  rewrite ^/ http://www.b.org/403.html;
                                                         }
                                 }

在www.a.com中设置引用b.org中images的图片:

[root@localhost a.com]# vi index.html 
<h1>www.a.com</h1>
<img src="http://www.b.org/images/1.jpg">

wKiom1ZG542Shde9AABcJW9gk0s003.png

6.状态页

location /status{

stub_status on;

access_log off;

allow 

deny all;

}

wKioL1ZGyAKCLqwIAABWOff2kJA508.png

页面解释:

当下处于活动状态的总数

接受的总数 已经建立和处理总数 请求的总数

正在接受的并发请求个数,正在读取的个数或发往客户端的 ,长连接中的处于活动状态的值

7、if判断语句

在location中使用if语句可以实现条件判断,其通常有一个return语句,且一般与有着last或break标记的rewrite规则一同使用。但其也可以按需要使用在多种场景下,需要注意的是,不当的使用可能会导致不可预料的后果。

location / {

if ($request_method == “PUT”) {

proxy_pass http://upload.magedu.com:8080;

if ($request_uri ~ "\.(jpg|gif|jpeg|png)$") {

proxy_pass http://imageservers;

break;

}

}

upstream imageservers {

server 172.16.100.8:80 weight 2;

server 172.16.100.9:80 weight 3;

}

if语句中的判断条件

正则表达式匹配:

==: 等值比较;

~:与指定正则表达式模式匹配时返回“真”,判断匹配与否时区分字符大小写;

~*:与指定正则表达式模式匹配时返回“真”,判断匹配与否时不区分字符大小写;

!~:与指定正则表达式模式不匹配时返回“真”,判断匹配与否时区分字符大小写;

!~*:与指定正则表达式模式不匹配时返回“真”,判断匹配与否时不区分字符大小写;

文件及目录匹配判断:

-f, !-f:判断指定的路径是否为存在且为文件;

-d, !-d:判断指定的路径是否为存在且为目录;

-e, !-e:判断指定的路径是否存在,文件或目录均可;

-x, !-x:判断指定路径的文件是否存在且可执行;

你可能感兴趣的:(nginx)