Nginx介绍及使用

   Nginx(engine x)是一个高性能的HTTP和反向代理服务器, 也是一个IMAP/POP3/SMTP服务器. Nginx是由IgorSysoev为俄罗斯访问量第二的Rambler.ru站点开发的, 第一个公开版本在2004年发布. 因为它的稳定性, 丰富的功能集, 示例配置文件和低系统资源的消耗而闻名. Nginx是一款轻量级的Web服务器/反向代理服务器及电子邮件代理服务器, 并在一个BSD-like协议下发行. 其特点是占用内存少, 并发能力强.

Nginx的程序架构:

    master/worker

        一个master进程: 负责加载配置文件、管理worker进程、平滑升级

        一个或多个worker进程: 处理并响应用户请求

        缓存相关的进程:

            cache loader:载入缓存对象

            cache manager:管理缓存对象

    特性:异步、事件驱动和非阻塞

        并发请求处理:通过kevent/epoll/select

        文件IO:高级IO sendfile,异步,mmap

    nginx高度模块块:高度模块化,但其模块早期不支持DSO机制;近期版本支持动态装载和卸载;

        模块分类:

            核心模块:core module

            标准模块:

               Standard HTTP modules

               Optional HTTP modules

              Mail modules

              Stream modules

              3rd party modules

nginx的功用:

     静态的web资源服务器;

     结合FastCGI/uwSGI/SCGI等协议反代动态资源请求;

     http/https协议的反向代理;

     imap4/pop3协议的反抽代理;

     tcp/udp协议的反代;

nginx的安装配置:

官方的预制包:

http://nginx.org/packages/centos/7/x86_64/RPMS/

编译安装:

~]# yum install pcre-devel openssl-devel zlib-devel
~]# useradd -r nginx
~]#  ./configure --prefix=/usr/local/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.pid --lock-path=/var/run/nginx.lock --user=nginx --group=nginx \
 --with-http_ssl_module --with-http_v2_module --with-http_dav_module \
 --with-http_stub_status_module --with-threads --with-file-aio
~]# make && make install

配置:

配置文件的组成部分:

    主配置文件:nginx.conf, include conf.d/*.conf

    fastcgi, uwsgi,scgi等协议相关的配置文件

    mime.types:支持的mime类型

    主配置文件的配置指令:

        directive value [value2 …];

注意:

    (1) 指令必须以分号结尾;

    (2) 支持使用配置变量;

内建变量:由Nginx模块引入,可直接引用;

自定义变量:由用户使用set命令定义;

    set variable_name value;

引用变量:$variable_name

主配置文件结构:

main block:主配置段,也即全局配置段;

event {

    …

}:事件驱动相关的配置;

http {

    …

}:http/https 协议相关的配置段;

mail {

    …

}

stream {

    …

}

http协议相关的配置结构

http {
    ...
    ...:各server的公共配置
    server {
    ...
    }:每个server用于定义一个虚拟主机;
    server {
       	...
       	server_name
       	root
       	alias
       	location [OPERATOR] URL {
           	...
           	if CONDITION {
           	...
       	    	}
       	}
    }
}

main配置段常见的配置指令:

     分类:

     正常运行必备的配置

     优化性能相关的配置

     用于调试及定位问题相关的配置

     事件驱动相关的配置

    正常 运行必备的配置:

1、user

Syntax: user user [group];

Default: user nobody nobody;

Context: main

2、pid /PATH/TO/PID_FILE;

指定存储nginx主进程进程号码的文件路径;

3、include file | mask;

指明包含进来的其它配置文件片断;

4、load_module file;

指明要装载的动态模块;

性能优化相关的配置:

1、worker_processes number | auto;

worker进程的数量;通常应该为当前主机的cpu的物理核心数;

2、worker_cpu_affinity cpumask …;

worker_cpu_affinity auto [cpumask];

CPU MASK:

00000001:0号CPU

00000010:1号CPU

… …

3、worker_priority number;

指定worker进程的nice值,设定worker进程优先级;[-20,20]

4、worker_rlimit_nofile number;

worker进程所能够打开的文件数量上限;

调试、定位问题:

1、daemon on|off;

是否以守护进程方式运行Nignx;

2、master_process on|off;

是否以master/worker模型运行nginx;默认为on;

3、error_log file [level];

事件驱动相关的配置:

events {

    …

}

1、worker_connections number;

Context: events

每个worker进程所能够打开的最大并发连接数数量, 默认512;

worker_processes * worker_connections

2、use method;

Context: events

指明并发连接请求的处理方法, 一般不用特别指出;

use epoll;

3、accept_mutex on | off;

Context: events

处理新的连接请求的方法;on意味着由各worker轮流处理新请求,Off意味着每个新请求的到达都会通知所有的worker进程;

一. 与套接字相关的配置

1、server { … }

配置一个虚拟主机;

server {
    listen address[:PORT]|PORT;
    server_name SERVER_NAME;
    root /PATH/TO/DOCUMENT_ROOT;
}

2、

listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE
listen address[:port] [default_server] [ssl] [http2 | spdy]  [backlog=number] [rcvbuf=size] [sndbuf=size]

3、server_name name …;

     指明虚拟主机的主机名称;后可跟多个由空白字符分隔的字符串;

     支持*通配任意长度的任意字符;server_name *.magedu.com

     支持~起始的字符做正则表达式模式匹配;server_name ~^www\d+\.magedu\.com$

     匹配机制:

         (1) 首先是字符串精确匹配;

         (2) 左侧*通配符;

         (3) 右侧*通配符;

         (4) 正则表达式;

4. tcp_nodelay on|off ;

在keeplived模式下的连接是否启用TCP_NODELAY选项(是否关闭延迟发送)

5. sendfile on|off;  – 是否使用sendfile功能; 

默认关闭

context : http, server, location, if in location

示例 :

location /video/ {
    sendfile on;
    tcp_nopush on;
    aio on;
}

二. 路径相关的配置 :

1. root – 定义web站点的根路径映射, 用于 指明用户请求的url所对应的本地文件系统上的文档所在目录路径;

语法 : root path;

Context : http, server, location, if in location.

2. location – 在一个server中location配置段可存在多个, 用于实现从uri到文件系统的路径映射; nginx会根据用户请求的URI来检查定义的所有location, 并找出一个最佳匹配, 而后应用其配置;

Syntax:

location [ = | ~ | ~* | ^~ ] uri { … }

location @name { … }

Context : server, location

=  : 对URI做精确匹配;

~  : 对URI做正则表达式模式匹配, 区分字符大小写;

~* : 对URI做正则表达式模式匹配, 不区分字符大小写;

^~ : 对URI的左半部分做匹配检查, 不区分字符大小写;

不带符号 : 匹配起始于此uri的所有的uri, 一般为uri提供默认配置;

匹配优先级 : '=' > '^~' > '~/~*' > '不带符号'

3. alias 

定义路径别名, 文档映射的另一种机制;

Syntax : alias path;

Context : location

示例 1 :

location /i/ {
    alias /data/w3/images/;
}
如果访问"/i/top.gif", 文件 "/data/w3/images/top.gif"会被发送.

示例 2 :

location /i/ {
    root /data/w3/;
}
如果访问"/i/top.gif", 文件"/data/w3/i/top.gif"会被发送

注意 : location中使用root指令和alias指令的意义不同;

     (a) root, 给定的路径对应于location中的/uri/左侧的 '/';

     (b) alias, 给定的路径对应于location中的/uri/右侧的 '/';

4. index file; – 定义默认主页资源

context : http, server, location

5. error_page code…[=[response]] uri;

context : http, server, location, if in location

自定义错误页面信息; 

6.  try_files file … uri;

try_files file … =code;

Default:

Context: server, location

检查指定顺序中文件的存在,并使用第一个找到的文件进行请求处理; 在当前上下文中执行处理。

location / {
    try_files $uri $uri/ @drupal;
}

location ~ \.php$ {
   try_files $uri @drupal;

   fastcgi_pass ...;

   fastcgi_param SCRIPT_FILENAME /path/to$fastcgi_script_name;
   fastcgi_param SCRIPT_NAME     $fastcgi_script_name;
   fastcgi_param QUERY_STRING    $args;

   ... other fastcgi_param's
}

location @drupal {
   fastcgi_pass ...;

   fastcgi_param SCRIPT_FILENAME /path/to/index.php;
   fastcgi_param SCRIPT_NAME     /index.php;
   fastcgi_param QUERY_STRING    q=$uri&$args;

   ... other fastcgi_param's
}

三. 定义客户端请求的相关配置 :

1. keepalive_timeout timeout;

Context : http, server, location

保持连接的超时时长, 0表示禁止长连接, 默认为75秒

2. keepalive_requests number;

Context : http, server, location

默认100; 在一次长连接上所允许请求的资源的最大数量;

3. keepalive_disable none|browser(浏览器);

Context : http, server, location

设定对哪种浏览器禁用保持连接功能;

4. send_timeout time;

Context : http, server, location

设定向客户端发送响应报文的超时时长, 此处指两次写操作之间的间隔时长;

默认60秒;

5. client_body_buffer_size size;

Context : http, server, location

设置用于接收客户body请求报文的缓冲区大小; 

默认为16K; 超出此大小时, 其将被暂存到磁盘上的由client_body_temp_path指令所定义的位置;

6. client_body_temp_path path [level1 [level2 [level3]]];

Context : http, server, location

设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量;

level的数值 表示16进制数字的 位数, 最大为2, 每一级有 0~ 16 ~ 16×16 种变化.

示例:client_body_temp_path /var/tmp/client_body 1 2 2

四. 对客户端进行限制的相关配置 :

1. limit_rate rate; 

限制对客户端的响应传输速度, 单位是bytes/second, 0表示无限制;

Context : http, server, location, if in location

示例:

server {
    if ($slow) {
        set $limit_rate 4k;
    }
}

2. limit_except method … {…};

限制对指定的请求方法之外的其他方法的使用客户端;

示例:

limit_except GET {
    allow 192.168.1.0/32;
    deny all;
}

五. 文件操作优化的配置:

1. aio on|off|threads[=pool]; 

Context: http, server, location

是否启用aio功能(异步IO);

示例:

location /video/ {
    aio on;
    output_buffers 1 64k;
}

示例2:

location /video/ {
    sendfile	on;
    aio	        on;
    directio    8m;
}

2. directio size | off;

Context: http, server, location

在linux主机上启用O_DIRECT标记, 此处意味文件大于等于给定的大小时使用.

3. open_file_cache off;

open_file_cache max=N [inactive=time];

  默认关闭

  Context : http, server, location

Configures a cache that can be store, 配置一个可存储的高速缓存;

nginx可以缓存以下三种信息

     (1) 文件描述符, 文件大小, 和最近一次的修改事件;

     (2) 打开的目录结构;

     (3) 没有找到的或者没有权限访问的文件的相关信息.

max=M : 可缓存的缓存项上限; 达到上限后会使用LRU算法实现缓存管理;

LRU : least recently used

inactive=time : 缓存项的非活动时长, 在此处指定的时长;

示例: 

open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_users 2;
open_file_cache_errors on;

4. open_file_cache_valid time;

缓存项有效性的检查频率, 默认60S

5. open_file_cache_min_uses number;

在open_file_cache指令的inactive参数指定的时长内, 至少应该被命中多少次方可被归类为活动项;

6. open_file_cache_errors on|off;

是否缓存查找时发生错误的文件一类的信息;

六. ngx_http_access_module模块  – 实现基于ip的访问控制功能;

示例:

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

1. allow address | CIDR | unix: | all;

Context: http, server, location, limit_except

2. deny address | CIDR | unix: | all;

Default:

Context: http, server, location, limit_except

七. ngx_http_auth_basic_module模块

实现基于用户的访问控制, 使用basic机制进行用户认证;

示例:

location {
    auth_basic "closed site";
    auth_basic_user_file  conf/htpasswd;
}

1. auth_basic string | off; 

是否启用登陆验证.

Context:  http, server, location, limit_except

2. auth_basic_user_file path;

Context:  http, server, location, limit_except

注意: htpasswd 命令有httpd-tools提供;

八. ngx_http_stub_status_module模块  – 用于输出nginx的基本信息

1. stub_status

示例:

location /basic_status {
    stub_status;
}

输出结果如下:

Active connections: 291 

server  accepts   handled   requests

       16630948  16630948  31070465 

Reading: 6  Writing: 179  Waiting: 106 

Active connections : 活动状态的客户端连接数;

           accepts : 已经接受的客户端请求的总数;

           handled : 已经处理完成的客户端请求的总数;

          requests : 客户端发来的总的请求数;

           Reading : 处于读取客户端请求报文首部的连接的连接数;

           Writing : 处于向客户端发送响应报文过程中的链接数;

           Waiting : 处于等待客户端发出请求的空闲连接数;

九. ngx_http_log_module模块

用来管理访问日志

1.  log_format name string…;

Context : http

string可以使用nginx核心模块及其他模块内嵌的变量;

2.  access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

access_log off;

访问日志文件路径, 格式及相关的缓冲配置

buffer=size (临时存储的大小)

flush=time(多长时间写一次磁盘)

3.  open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];

open_log_file_cache off;

缓存各日志文件相关的元数据信息;

max=N – 最大文件文件描述符数量;

inactive – 非活动时长;

min_user – 在inactive指定的时长内, 访问大于等于此值方可被当作活动项;

valid – 验证缓存中各缓存项是否为活动项的时间间隔;

十. ngx_http_rewrite_module

将用户请求的URI基于regex所描述的模式进行检查, 而后完成替换

1. rewrite regex replacement[flag]

Context : server, location, if

将用户请求的URI基于regex所描述的模式进行检查, 匹配到时将其替换为replacement所指定的新的URI;

注意:

    如果在同一级配置块中存在多个rewrite规则, 那么会自上而下逐个检查; 被某条规则替换完成后, 会重新启动新一轮的检查, 因此, 隐含循环机制; [flag]标志位用于控制此循环机制;

    如果replacement是以http://或https://开头的绝对路径, 则替换结果会直接以重定向返回给客户端;

301 : 永久重定向;

[flag]

    last : 默认行为; 重写完成后停止对当前URI在当前location中后续的其他重写操作, 而后对新的URI启动新一轮重写检查; 提前重启新一轮循环;

    break : 重写完成后停止对当前URI在当前location中后续的其他重写操作, 而后直接跳转至重写规则配置块之后的其他配置; 结束循环;

    redirect : 重写完成后以临时重定向方式直接返回重写后生成的新URI给客户端, 由客户端重新发起请求; 不能以http://和https://开头;

    permanent : 重写完成后以永久重定向方式直接返回重写后生成的新URI给客户端, 由客户端重新发起请求; 

示例 :

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

2. Syntax: return code [text];

return code URL;

return URL;

Context: server, location, if

Stops processing and returns the specified code to a client; – 停止处理并将指定的代码返回给客户端;

3. rewrite_log on | off;

是否 开启重写日志;

4. if(condition) {…}

引入一个新的配置上下文; 条件满足是, 执行配置块中的配置命令;

Context : server, location;

condition:

比较操作符

==

!=

  ~ : 模式匹配, 区分字符大小写

 ~* : 模式匹配,不区分字符大小写

 !~ : 模式不匹配, 区分字符大小写

!~* : 模式不匹配, 不区分字符大小写

文件及目录存在性判断:

-e, !-e

-f, !-f

-d, !-d

-x, !-x

示例:

if ($http_user_agent ~ MSIE) {
    rewrite ^(.*)$ /msie/$1 break;
}
if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
    set $id $1;
}
if ($request_method = POST) {
    return 405;
}
if ($slow) {
    limit_rate 10k;
}
if ($invalid_referer) {
    return 403;
}

5. set $variable value;

Sets a value for the specified variable. 设置指定变量的值

十一. ngx_http_gzip_module模块 

在给客户端响应时, 这个模块将一些需要过滤的文件信息压缩传送, 以提高速度.

1. gzip on | off;

Context : http, server, location, if in location

是否开启gzipping 响应

2. gzip_comp_level level;

设置gzipping responses的压缩等级, 1~9, 数字越高压缩比越大, 占用资源越多;

3. gzip_disable regex…;

4. gzip_min_length length;

启用压缩功能的响应报文的大小阈值; 默认20

5. gzip_buffers number size;

支持实现压缩功能时为其配置的缓冲区数量及每个缓冲区的大小;

6. gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any …;

nginx作为代理服务器接收到从被代理服务器发送的响应报文后, 在什么条件下启用压缩功能;

off : 对代理的请求不启用

no-cache, no-store, private : 表示从被代理服务器收到的响应报文首部的cache-Control的值为此三者中任何一个, 则启用压缩功能;

7. gzip_types mime-type …;

Context : http, server, location

压缩过滤器, 仅对此处设定的MIME类型的内容启用压缩功能;

示例 :

http {
    ...
    gzip on;
    gzip_comp_level 6;
    #gzip_disable .*MSIE.*;
    gzip_types (此处查看mime.types, 根据需要选择);
    gzip_min_length 1K;
}

十二. ngx_http_fastcgi_module模块

1. fastcgi_pass address;

Context : location, if in location

address为fsctcgi server的地址; 

2. fastcgi_index name;

Context : http, server, location

fastcgi默认的主页资源

3. fastcgi_param parameter value [if_not_empty];

配置示例 1:

前提: 配置好php-fpm server和mariadb-server服务

location ~* \.php$ {
    root /usr/share/nginx/html;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html$fastcgi_script_name;
    include    fastcgi_param;
}

配置示例 2:

location ~* ^/(pm_status|ping)$ {
    include fastcgi_param;
    fastcgi_pass	127.0.0.1:9000;
    fastcgi_param   SCRIPT_FILENAME  $fastcgi_script_name;
}

4. fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

定义fastcgi的缓存, 缓存位置为磁盘上的文件系统, 由path所指定路径来定义;

  levels=levels : 缓存目录的层级数量, 以及每一及的目录数量; levels=1:2:2, 三级缓存, 最大为2 , 是十六进制数字的位数

keys_zone=name:size     k/v映射的内存空间的名称及大小

inactive=time : 非活动时长;

max_size=size: 磁盘上用于缓存数据的缓存空间上限;

5. fastcgi_cache zone|off;

调用指定的缓存空间来缓存数据

Context : http, server, location

6. fastcgi_cache_key string

定义用于缓存项的key的字符串;

7. fastcgi_cache_method GET | HEAD | POST …;

为哪些请求方法使用缓存; 

8. fastcgi_cache_min_uses number;

缓存空间中缓存项在inactive定义的非活动时间内至少要被访问到, 此处指定的次数方可被认作活动项;

9. fastcgi_cache_valid [code…] time;

不同的响应码各自的缓存时长;

示例:

http {
    ...
    fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2:1 keys_zone=fcgi:20m inactive=120s;
    ...
    server {
        ...
        location ~* \.php$ {
            ...
            fastcgi_cache fcgi;
            fastcgi_cache_key $request_uri;
            fastcgi_cache_valid 200 302 10m;
            fastcgi_cache_valid 301 1h;
            fastcgi_cache_valid any 1m;
            ...
        }
        ...
    }
    ...
}

10. fastcgi_keep_conn on | off;

是否启用fastcgi的保持连接功能

十三. ngx_http_ssl_module

1. ssl on | off;

Context : http, server

是否开始ssl模块, 默认关闭;

2. ssl_certificate file;

当前虚拟主机使用PEM格式的证书文件;

3. ssl_certificate_key file;

当前虚拟主机上与其证书匹配的私钥文件;

4. ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];

支持的ssl协议版本, 默认为后三个;

5. ssl_session_cache off | none | [buildin[:size]] [shared:name:size];

builtin[:size]: 使用OpenSSL内建的缓存,此缓存为每worker进程私有;

[shared:name:size]: 在各worker之间使用一个共享的缓存;

6. ssl_session_timeout time;

客户端一侧的连接可以服用ssl session cache中缓存的ssl参数的有效时长;

配置示例 :

server {
    listen 443 ssl;
    server_name www.magedu.com;
    root /vhosts/ssl/htdocs;
    ssl on;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ssl_session_cache shared:sslcache:20m;
}

十四. ngx_http_referer_module模块

The ngx_http_referer_module module is used to block access to a site for requests with invalid values in the “Referer” header field. 

1、valid_referers none | blocked | server_names | string …;

定义referer首部的合法可用值;

                   none : 请求报文首部没有referer首部;

                blocked : 请求报文的referer首部没有值;

           server_names : 参数,其可以有值作为主机名或主机名模式;

       arbitrary_string : 直接字符串,但可使用*作通配符;

     regular expression : 被指定的正则表达式模式匹配到的字符串;要使用~打头,例如 ~.*\.magedu\.com;

配置示例:

valid_referers none block server_names *.magedu.com *.mageedu.com magedu.* mageedu.* ~\.magedu\.;
if($invalid_referer) {
return 403;
}

十五. ngx_http_proxy_module模块

1、proxy_pass URL;

Context: location, if in location, limit_except

注意:

(1) proxy_pass后面的路径不带uri时,其会将location的uri传递给后端主机;

server {
    ...
    server_name HOSTNAME;
    location /uri/ {
        proxy http://host[:port];
    }
    ...
}

#http://HOSTNAME/uri --> http://host/uri

(2) proxy_pass后面的路径是一个uri时,其会将location的uri替换为proxy_pass的uri;

server {
    ...
    server_name HOSTNAME;
    location /uri/ {
        proxy http://host/new_uri/;
    }
    ...
}
#http://HOSTNAME/uri/ --> http://host/new_uri/

(3) 如果location定义其uri时使用了正则表达式的模式,则proxy_pass之后必须不能使用uri; 用户请求时传递的uri将直接附加代理到的服务的之后;

server {
    ...
    server_name HOSTNAME;
    location ~|~* /uri/ {
        proxy http://host;
    }
    ...
}
#http://HOSTNAME/uri/ --> http://host/uri/;

2、proxy_set_header field value;

设定发往后端主机的请求报文的请求首部的值; Context: http, server, location

proxy_set_header X-Real-IP  $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

3、proxy_cache_path

定义可用于proxy功能的缓存;Context: http

proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

4、proxy_cache zone | off;

指明要调用的缓存,或关闭缓存机制;Context: http, server, location

5、 proxy_cache_key string;

缓存中用于“键”的内容;

默认值:proxy_cache_key $scheme$proxy_host$request_uri;

6、proxy_cache_valid [code …] time;

定义对特定响应码的响应内容的缓存时长;

定义在http{…}中;

proxy_cache_path /var/cache/nginx/proxy_cache levels=1:1:1 keys_zone=pxycache:20m max_size=1g;

定义在需要调用缓存功能的配置段,例如server{…};

proxy_cache pxycache;
proxy_cache_key $request_uri;
proxy_cache_valid 200 302 301 1h;
proxy_cache_valid any 1m;

7、proxy_cache_use_stale

proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off …;

Determines in which cases a stale cached response can be used when an error occurs during communication with the proxied server.

8、proxy_cache_methods GET | HEAD | POST …;

If the client request method is listed in this directive then the response will be cached. “GET” and “HEAD” methods are always added to the list, though it is recommended to specify them explicitly. 

9、proxy_hide_header field;

By default, nginx does not pass the header fields “Date”, “Server”, “X-Pad”, and “X-Accel-…” from the response of a proxied server to a client. The proxy_hide_header directive sets additional fields that will not be passed.

10、proxy_connect_timeout time;

Defines a timeout for establishing a connection with a proxied server. It should be noted that this timeout cannot usually exceed 75 seconds.

默认为60s;

十六. buffer相关的配置

ngx_http_headers_module模块

The ngx_http_headers_module module allows adding the “Expires” and “Cache-Control” header fields, and arbitrary fields, to a response header.

向由代理服务器响应给客户端的响应报文添加自定义首部,或修改指定首部的值;

1、add_header name value [always];

添加自定义首部;

add_header X-Via  $server_addr;

add_header X-Accel $server_name;

2、expires [modified] time;

expires epoch | max | off;

用于定义Expire或Cache-Control首部的值;

ngx_http_upstream_module模块 

The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, and memcached_pass directives.

十七. ngx_http_upstream_module模块 

The ngx_http_upstream_module module is used to define groups of servers that can be referenced by the proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, and memcached_pass directives.

1、upstream name { … }

定义后端服务器组,会引入一个新的上下文;Context: http

upstream httpdsrvs {
    server ...
    server...
    ...
}

2、server address [parameters];

在upstream上下文中server成员,以及相关的参数;Context: upstream

address的表示格式:

unix:/PATH/TO/SOME_SOCK_FILE

IP[:PORT]

HOSTNAME[:PORT]

parameters:

    weight=number # 权重,默认为1;
 max_fails=number # 失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用;
fail_timeout=time # 设置将服务器标记为不可用状态的超时时长;
        max_conns # 当前的服务器的最大并发连接数;
           backup # 将服务器标记为“备用”,即所有服务器均不可用时此服务器才启用;
             down # 标记为“不可用”;

3、least_conn;

最少连接调度算法,当server拥有不同的权重时其为wlc;

4、 ip_hash;

源地址hash调度方法;

5、hash key [consistent];

基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者的组合;

作用:将请求分类,同一类请求将发往同一个upstream server;

If the consistent parameter is specified the ketama consistent hashing method will be used instead.

示例:

hash $request_uri consistent;

hash $remote_addr;

6、keepalive connections;

为每个worker进程保留的空闲的长连接数量;

nginx的其它的二次发行版:

tengine

OpenResty

十八. ngx_stream_core_module模块

模拟反代基于tcp或udp的服务连接,即工作于传输层的反代或调度器;

1、stream { … }

定义stream相关的服务;Context:main

stream {
    upstream sshsrvs {
        server 192.168.22.2:22; 
        server 192.168.22.3:22; 
        least_conn;
    }
    server {
    listen 10.1.0.6:22022;
    proxy_pass sshsrvs;
    }
}

2、listen

listen address:port [ssl] [udp] [proxy_protocol] [backlog=number] [bind] [ipv6only=on|off] [reuseport] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];

原创文章,作者:black_fish,如若转载,请注明出处:http://www.178linux.com/54739

(0)
上一篇 2016-11-11 08:41
下一篇 2016-11-11 12:39

相关推荐

  • 马哥linux0803作业内容

    1. 创建sysadmins组 将用户user1,user2,user3加入sysadmins组中 将user3设置为sysadmins的管理员 用user3登录,将user2从组中移除 设置sysadmins的密码centos 设置user1 在创建新文件时,文件的所属组为sysadmins 删除user1…3 删除sysadmins 2、三种权限rwx对…

    Linux干货 2016-08-08
  • Linux磁盘分区创建及bash 简单应用

    1、创建一个10G分区,并格式为ext4文件系统; (1)要求其block大小为2048,预留空间百分比为2,卷标为MYDATA,默认挂载属性包含acl; (2)挂载至/data/mydata目录,要求挂载是禁止程序自动运行,并且更新文件的访问时间戳; [root@danry ~]# fdisk /dev/sdb Welcome to fdisk (util…

    2017-09-11
  • 第二天作业

    一、Linux 文件管理类命令   cd、pwd、mkdir、rmdir、ls、cp、rm、mv、cat、tac、more、less、head、tail、touch     1、目录类相关命令     cd:change directory 切换目录     pwd:print …

    Linux干货 2016-08-22
  • 网络基础知识子网划分

    一、某公司申请到一个C 类IP 地址,但要连接6 个的子公司,最大的一个子 公司有26 台计算机,每个子公司在一个网段中,则子网掩码应设为?  根据要划分的子网数量来算子网掩码的。2的M次方大于等于N。其中M是划分子网时要借的位数。N是要划分的子网数。 将需求代入公式,M=3,C类IP默认的掩码为24位,再从主机位中借来3位,就是27位。二进制表示…

    Linux干货 2016-09-06
  • Linux安全和加解密

    概述:     所有业务的正常运转,离不开一个安全的运行环境,系统安全性直接关系到业务稳定、可靠、以及可用性,本章就介绍一些系统安全相关的话题,具体包括:        1、加密基础概念     2、CA和证书的基础概念  &nb…

    Linux干货 2016-09-23
  • Linux软件包安装—-卷一软件包管理rpm方式安装程序

    rpm方式手动安装程序,可能需要”人工智能”的方式手动去处理程序依赖问题

    Linux干货 2017-12-02