zoukankan      html  css  js  c++  java
  • Nginx学习.md

    正常运行的必备配置

    user

    Syntax: user user [group];
    Default: user nobody nobody;
    Context: main

    指定运行worker进程的用户 和组。

    pid

    Syntax: pid file;
    Default: pid nginx.pid;
    Context: main

    指定nginx的pid文件;

    worker_rlimit_nofile

    Syntax: worker_rlimit_nofile number;
    Default: —
    Context: main

    指定一个worker进程所能够打开的最大文件句柄数;

    worker_rlimit_sigpending

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

    优化性能相关的配置

    worker_processes

    Syntax: worker_processes number | auto;
    Default: worker_processes 1;
    Context: main

    worker线程的个数;通常应该为物理CPU核心个数减1;如果设置成auto则nginx的版本是1.10以上。

    worker_cpu_affinity

    Syntax: worker_cpu_affinity cpumask ...;
    worker_cpu_affinity auto [cpumask];
    Default: —
    Context: main

    绑定worker进程至指定的CPU上运行;例如四核CPU则是:0001、0010、0100、1000。几核CPU就有几个状态位,如果想要在指定的CPU核心运行则在其置位为1,注意cpumask上不能同时出现两个1。

    举例

    worker_processes 2;
    worker_cpu_affinity 0100 1000;
    # nginx -s reload
    #  ps axo command,pid,psr |grep nginx |grep -v grep
    nginx: master process nginx  4533   1
    nginx: worker process        4638   2
    nginx: worker process        4639   3
    

    timer_resolution

    Syntax: timer_resolution interval;
    Default: —
    Context: main

    该配置指令允许用户减少调用gettimeofday()的次数。默认情况下,该函数在每次I/O端口监听(比如epoll_wait)返回后都将被调用,而通过timer_resolution配置选项可以直接指定调用gettimeofday()函数的间隔时间。

    worker_priority

    Syntax: worker_processes number | auto;
    Default: worker_processes 1;
    Context: main

    定义worker进程的调度优先级,就像由nice命令完成的:负数意味着更高的优先级。 允许范围通常在-20到19之间变化。

    举例

    user nginx;
    worker_processes 2;
    worker_cpu_affinity 0100 1000;
    worker_priority -5;
    # nginx -s reload
    # ps axo command,pid,psr,nice |grep nginx |grep -v grep
    nginx: master process nginx  4533   1   0
    nginx: worker process        4779   2  -5
    nginx: worker process        4780   3  -5
    

    事件相关的配置

    accept_mutex

    Syntax: accept_mutex on | off;
    Default: accept_mutex off;
    Context: events

    各worker接收用户的请求的负载均衡锁;启用时,表示用于让多个worker轮流地、序列化地响应新请求; 否则,将向所有worker进程通知有关新连接的信息,如果新连接数量较少,则某些worker进程可能只会浪费系统资源。
    在版本1.11.3之前,默认值为on。

    lock_file

    Syntax: lock_file file;
    Default: lock_file logs/nginx.lock;
    Context: main

    nginx使用锁定机制来实现accept_mutex和序列化对共享内存的访问。 在大多数系统上,锁是使用原子操作实现的,并且此伪指令被忽略。

    accept_mutex_delay

    Syntax: accept_mutex_delay time;
    Default: accept_mutex_delay 500ms;
    Context: events

    如果启用accept_mutex,则指定如果另一个worker进程当前正在接受新连接,worker进程将尝试重新启动接受新连接的最长时间。

    use

    Syntax: use method;
    Default: —
    Context: events

    定义使用的事件模型;建议让Nginx自动选择;

    worker_connections

    Syntax: worker_connections number;
    Default: worker_connections 512;
    Context: events

    每个worker进程所能够响应的最大并发请求数量;应该记住,这个数字包括所有连接(例如与代理服务器的连接等),而不仅仅是与客户端的连接。 另一个考虑是同时连接的实际数量不能超过打开文件的最大数量的当前限制,可以通过worker_rlimit_nofile更改。
    在nginx中设置的最大连接数为:
    worker_proceses * worker_connections

    用于调试、定位问题

    daemon

    Syntax: daemon on | off;
    Default: daemon on;
    Context: main

    确定nginx是否应该成为守护进程。 主要用于开发过程中。

    master_process

    Syntax: master_process on | off;
    Default: master_process on;
    Context: main

    是否以master/worker模型运行nginx;

    error_log

    Syntax: error_log file [level];
    Default: error_log logs/error.log error;
    Context: main, http, mail, stream, server, location

    错误日志文件及其级别;出于调试的目的,可以使用debug级别,但此级别只有在编译nginx时使用了--with-debug选项才有效;

    虚拟主机相关的配置

    server

    Syntax: server { ... }
    Default: —
    Context: http

    设置虚拟服务器的配置。

    listen

    Syntax: listen address[:port] [default_server] [ssl] [http2 | spdy]
    listen port [default_server] [ssl] [http2 | spdy]
    Default: listen *:80 | *:8000;
    Context: server

    设置IP的地址和端口,或者服务器将接受请求的UNIX域套接字的路径。 可以指定地址和端口,或仅指定地址或仅指定端口。
    default_server:设置默认虚拟主机;用于基于IP地址,或使用了任意不能对应于任何一个server的name时所返回站点;
    ssl:用于限制只能通过ssl连接提供服务;

    例如

    listen 127.0.0.1:8000;
    listen 127.0.0.1;
    listen 8000;
    listen *:8000;
    listen localhost:8000;
    

    server_name

    Syntax: server_name name ...;
    Default: server_name "";
    Context: server

    设置虚拟服务器的名称。后可跟一个或多个主机名;名称还可以使用通配符和正则表达式(~);
    (1) 首先做精确匹配;例如:www.example.com
    (2) 左侧通配符;例如:*.example.com
    (3) 右侧通配符,例如:www.example.*
    (4) 正则表达式,例如:~^.*.example.com$
    (5) default_server

    location

    Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
    location @name { ... }
    Default: —
    Context: server, location

    允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location块中的配置所处理;简言之,即用于为需要用到专用配置的uri提供特定配置;

    • =:URI的精确匹配;
    • ~:做正则表达式匹配,区分字符大小写;
    • ~*:做正则表达式匹配,不区分字符大小写;
    • ^~:URI的左半部分匹配,不区分字符大小写;

    匹配优先级:精确匹配=、^~、~或~*、不带符号的URL;

    举例

    location = / {
        [ configuration A ]
    }
    
    location / {
        [ configuration B ]
    }
    
    location /documents/ {
        [ configuration C ]
    }
    
    location ^~ /images/ {
        [ configuration D ]
    }
    
    location ~* .(gif|jpg|jpeg)$ {
        [ configuration E ]
    }
    

    “/”请求将匹配配置A,“/index.html”请求将匹配配置B,“/documents/document.html”请求将匹配配置C,“/images/1.gif”请求将匹配配置D,并且“/documents/1.jpg”请求将匹配配置E.

    root

    Syntax: root path;
    Default: root html;
    Context: http, server, location, if in location

    设置请求的根目录。路径值可以包含变量,$document_root和$ realpath_root除外。
    只有通过向root指令的值添加一个URI,即可构建文件的路径。 如果必须修改URI,则应使用alias伪指令。
    举例

    # tree /data/website/
    /data/website/
    |-- index.html
    `-- test
        `-- index.html
    
    nginx.conf:
    location /test {
      root /data/website/;
    }
    
    # curl http://www.a.com/test/
    /data/website/
    

    alias

    Syntax: alias path;
    Default: —
    Context: location

    定义指定位置的替换。路径值可以包含变量,$document_root和$ realpath_root除外。如果在使用正则表达式定义的位置内使用别名,则此类正则表达式应包含捕获,并且别名应引用这些捕获。
    举例

    location /test {
      root /data/website;
    }
    
    # curl http://www.a.com/test/
    /data/website/test/
    

    注意:
    root指令:给定的路径对应于location的“/”这个URL;
    /test/index.html --> /data/website/test/index.html
    alias指令:给定的路径对应于location的“/uri/"这个URL;
    /test/index.html --> /data/website/index.html

    error_page

    Syntax: error_page code ... [=[response]] uri;
    Default: —
    Context: http, server, location, if in location

    根据http状态码重定向错误页面。
    举例

    nginx.conf:
    location / {
      root /data/website;
    }
    error_page  404              /404.html
    # echo 404.page >/data/website/404.html
    # curl http://www.a.com/aaaaa
    404.page
    # curl http://www.a.com/aaaaa -I
    HTTP/1.1 404 Not Found
    Server: nginx/1.10.1
    Date: Sat, 11 Feb 2017 16:39:24 GMT
    Content-Type: text/html
    Content-Length: 9
    Connection: keep-alive
    ETag: "589f3e1d-9"
    

    自定义状态码:

    error_page  404 =201             /404.html;
    # curl http://www.a.com/aaaaa -I
    HTTP/1.1 201 Created
    Server: nginx/1.10.1
    Date: Sat, 11 Feb 2017 16:43:11 GMT
    Content-Type: text/html
    Content-Length: 9
    Connection: keep-alive
    ETag: "589f3e1d-9"
    # curl http://www.a.com/aaaaa 
    404.page
    

    try_files

    Syntax: try_files file ... uri;
    try_files file ... =code;
    Default: —
    Context: server, location

    尝试查找第1至第N-1个文件,第一个即为返回给请求者的资源;若1至N-1文件都不存在,则跳转至最一个uri(必须不能匹配至当前location,而应该匹配至其它location,否则会导致死循环);
    举例

    nginx.conf:
      root /data/website;
           location /test {
      try_files /test/1.html /test/2.html /test/3.html @abc;
    }
         location @abc {
          rewrite ^/(.*)$ http://baidu.com;
    }
    # ls /data/website/test/
    3.html
    # curl http://www.a.com/test/1.html
    33333
    

    网络连接相关的配置

    keepalive_timeout

    Syntax: keepalive_timeout timeout [header_timeout];
    Default: keepalive_timeout 75s;
    Context: http, server, location

    第一个参数设定keepalive连接的超时时长;0表示禁止长连接;默认为75s;可选的第二个参数在“Keep-Alive:timeout = time”响应报文header字段中设置一个值。 两个参数可能不同。“Keep-Alive:timeout = time”头字段由Mozilla和Konqueror识别。 MSIE在大约60秒内关闭保持连接。

    keepalive_requests

    Syntax: keepalive_requests number;
    Default: keepalive_requests 100;
    Context: http, server, location
    This directive appeared in version 0.8.0.

    在keepalived连接上所允许请求的最大资源数量;默认为100;在发出最大数量的请求后,将关闭连接。

    keepalive_disable

    Syntax: keepalive_disable none | browser ...;
    Default: keepalive_disable msie6;
    Context: http, server, location

    指明禁止为何种浏览器使用keepalive功能; 浏览器参数指定将影响哪些浏览器。设置成msie6则在收到POST请求时禁用与旧版本的MSIE的保持活动连接。设置成safari则禁用与Mac OS X和Mac OS X类操作系统上的Safari浏览器的保持连接。设置成none则启用与所有浏览器的保持活动连接。

    tcp_nodelay

    Syntax: tcp_nodelay on | off;
    Default: tcp_nodelay on;
    Context: http, server, location

    对keepalive模式下的连接是否使用TCP_NODELAY选项;

    tcp_nopush

    Syntax: tcp_nopush on | off;
    Default: tcp_nopush off;
    Context: http, server, location

    是否启用TCP_NOPUSH(FREEBSE)或TCP_CORK(Linux)选项;仅在sendfile为on时有用;

    client_body_timeout

    Syntax: client_body_timeout time;
    Default: client_body_timeout 60s;
    Context: http, server, location

    定义读取客户端请求报文body的超时时间。 超时时间仅设置在两个连续读取操作之间的时间段,而不是用于传输整个请求体。 如果客户端在此时间内未发送任何内容,则会将408(请求超时)错误返回给客户端。

    send_timeout

    Syntax: send_timeout time;
    Default: send_timeout 60s;
    Context: http, server, location

    发送响应报文的超时时长,默认为60s; 超时仅在两个连续的写操作之间设置,而不是用于传输整个响应。 如果客户端在此时间内未收到任何内容,则连接将关闭。

    对客户端请求进行限制

    limit_except

    Syntax: limit_except method ... { ... }
    Default: —
    Context: location

    对指定范围之外的其它的方法进行访问控制; 方法参数可以是以下之一:GET,HEAD,POST,PUT,DELETE,MKCOL,COPY,MOVE,OPTIONS,PROPFIND,PROPPATCH,LOCK,UNLOCK或PATCH。 允许GET方法也允许HEAD方法。 可以使用ngx_http_access_module和ngx_http_auth_basic_module模块伪指令限制对其他方法的访问。
    举例

    nginx.conf:
    location /download {
    limit_except GET {
      allow 192.168.0.220;
      deny all;
    }
    }
    192.168.0.220:
    # curl -X GET -I http://www.a.com/download/test.img
    HTTP/1.1 200 OK
    Server: nginx/1.10.1
    Date: Sun, 12 Feb 2017 11:09:21 GMT
    Content-Type: application/octet-stream
    Content-Length: 209715200
    Last-Modified: Sat, 11 Feb 2017 17:17:06 GMT
    Connection: keep-alive
    ETag: "589f4712-c800000"
    Accept-Ranges: bytes
    # curl -X PUT -I http://www.a.com/download/test.img
    HTTP/1.1 405 Not Allowed
    Server: nginx/1.10.1
    Date: Sun, 12 Feb 2017 11:09:11 GMT
    Content-Type: text/html
    Content-Length: 173
    Connection: keep-alive
    192.168.0.201:
    # curl -X GET -I http://www.a.com/download/test.img 
    HTTP/1.1 200 OK
    Server: nginx/1.10.1
    Date: Sun, 12 Feb 2017 11:10:22 GMT
    Content-Type: application/octet-stream
    Content-Length: 209715200
    Last-Modified: Sat, 11 Feb 2017 17:17:06 GMT
    Connection: keep-alive
    ETag: "589f4712-c800000"
    Accept-Ranges: bytes
    # curl -X PUT -I http://www.a.com/download/test.img 
    HTTP/1.1 403 Forbidden
    Server: nginx/1.10.1
    Date: Sun, 12 Feb 2017 11:10:16 GMT
    Content-Type: text/html
    Content-Length: 169
    Connection: keep-alive
    

    limit_rate

    Syntax: limit_rate rate;
    Default: limit_rate 0;
    Context: http, server, location, if in location

    限制客户端每秒钟所能够传输的字节数,默认为0表示无限制; 速率以字节/秒指定。这是对每个请求设置限制,因此如果客户端同时打开两个连接,则总速率将是指定限制的两倍。
    在根据一定条件限制费率的情况下,速率限制也可以在$ limit_rate变量中设置。
    速率限制也可以在代理服务器响应的“X-Accel-Limit-Rate”报头字段中设置。 此功能可以使用proxy_ignore_headers,fastcgi_ignore_headers,uwsgi_ignore_headers和scgi_ignore_headers指令禁用。
    举例

    nginx.conf:
    location /download {
    limit_rate 20480;
    }
    download ]# dd if=/dev/zero of=./test.img  bs=200M count=1
    # wget http://www.a.com/download/test.img
    --2017-02-12 01:19:55--  http://www.a.com/download/test.img
    正在解析主机 www.a.com (www.a.com)... 192.168.0.220
    正在连接 www.a.com (www.a.com)|192.168.0.220|:80... 已连接。
    已发出 HTTP 请求,正在等待回应... 200 OK
    长度:209715200 (200M) [application/octet-stream]
    正在保存至: “test.img”
    
     0% [                                                                                                                                                    ] 245,760     20.0KB/s 剩余 2h 50m
    

    对内存或磁盘资源进行分配

    client_body_in_file_only

    Syntax: client_body_in_file_only on | clean | off;
    Default: client_body_in_file_only off;
    Context: http, server, location

    确定nginx是否应将整个客户端请求正文保存到文件中。
    当设置为on时,临时文件不会在请求处理后删除。
    值为clean将导致删除请求处理后剩余的临时文件。
    值为off不允许暂存。

    client_body_in_single_buffer

    Syntax: client_body_in_single_buffer on | off;
    Default: client_body_in_single_buffer off;
    Context: http, server, location

    确定nginx是否应将整个客户端请求正文保存在单个缓冲区中。

    client_body_buffer_size

    Syntax: client_body_buffer_size size;
    Default: client_body_buffer_size 8k|16k;
    Context: http, server, location

    设置用于读取客户机请求报文body的缓冲区大小。 在请求主体大于缓冲区的情况下,整个主体或仅其部分被写入临时文件。 默认情况下,缓冲区大小等于两个内存页。 这在x86,其他32位平台和x86-64上是8K。 在其他64位平台上通常为16K。

    client_body_temp_path

    Syntax: client_body_temp_path path [level1 [level2 [level3]]];
    Default: client_body_temp_path client_body_temp;
    Context: http, server, location

    定义用于存储保存客户端请求正文的临时文件的目录。 在指定的目录下最多可以使用三级子目录层次结构。

    client_header_buffer_size

    Syntax: client_header_buffer_size size;
    Default: client_header_buffer_size 1k;
    Context: http, server

    设置读取客户端请求报文header的缓冲区大小。 对于大多数请求,1K字节的缓冲区就足够了。 但是,如果请求包括长Cookie,或来自WAP客户端,它可能不适合1K。 如果请求行或请求头字段不适合该缓冲区,则分配由large_client_header_buffers指令配置的较大缓冲区。

    MIME类型相关的配置

    types

    Syntax: types { ... }
    Default: types {
    text/html html;
    image/gif gif;
    image/jpeg jpg;
    }
    Context: http, server, location

    将文件扩展名映射到MIME类型的响应。 扩展名不区分大小写。几个扩展可以映射到一个类型,例如:

    types {
        application/octet-stream bin exe dll;
        application/octet-stream deb;
        application/octet-stream dmg;
    }
    

    在conf / mime.types文件中,nginx分发了一个足够完整的映射表。
    要使特定位置发出所有请求的“application/octet-stream”MIME类型,可以使用以下配置:

    location /download/ {
        types        { }
        default_type application/octet-stream;
    }
    

    default_type

    Syntax: default_type mime-type;
    Default: default_type text/plain;
    Context: http, server, location

    定义响应的默认MIME类型。 可以使用types伪指令来将文件扩展名映射到MIME类型。

    文件操作优化相关的配置

    sendfile

    Syntax: sendfile on | off;
    Default: sendfile off;
    Context: http, server, location, if in location

    启用或禁用sendfile()的使用。
    从nginx 0.8.12和FreeBSD 5.2.1开始,aio可以用来为sendfile()预加载数据。
    在此配置中,使用SF_NODISKIO标志调用sendfile(),这导致它不会在磁盘I / O上阻塞,而是报告数据不在内存中。 然后,nginx通过读取一个字节来启动异步数据加载。 在第一次读取时,FreeBSD内核将一个文件的前128个字节加载到内存中,虽然下一次读取将只加载16K块的数据。 这可以使用read_ahead指令更改。
    Notes:在1.7.11之前,可以使用aio sendfile启用预加载。

    aio

    Syntax: aio on | off | threads[=pool];
    Default: aio off;
    Context: http, server, location
    This directive appeared in version 0.8.11.

    在FreeBSD和Linux上启用或禁用异步文件I / O(AIO)的使用。在Linux上,AIO可以从内核版本2.6.22开始使用。此外,有必要启用directio,否则读取将阻塞:

    location /video/ {
        aio            on;
        directio       512;
        output_buffers 1 128k;
    }
    

    directio

    Syntax: directio size | off;
    Default: directio off;
    Context: http, server, location
    This directive appeared in version 0.7.7.

    读取大于或等于指定大小的文件时,允许使用O_DIRECT标志(FreeBSD,Linux),F_NOCACHE标志(Mac OS X)或directio()函数(Solaris)。 该指令自动禁用(0.7.15)给定请求的sendfile的使用。

    open_file_cache

    Syntax: open_file_cache off;
    open_file_cache max=N [inactive=time];
    Default: open_file_cache off;
    Context: http, server, location

    配置可以存储以下内容的缓存:
    (1) 文件描述符、文件大小和最近一次的修改时间;
    (2) 打开的目录的结构;
    (3) 没有找到的或者没有权限操作的文件的相关信息;
    Notes:错误的缓存应该由open_file_cache_errors指令单独启用。

    该伪指令具有以下参数:

    • max:表示可缓存的最大条目上限;一旦达到上限,则会使用LRU算法从缓存中删除最近最少使用的缓存项;
    • inactive:在此处指定的时长内没有被访问过的缓存项是为非活动缓存项,因此直接删除;
    • off:禁用高速缓存。

    open_file_cache_errors

    Syntax: open_file_cache_errors on | off;
    Default: open_file_cache_errors off;
    Context: http, server, location

    是否缓存找不到其路径的文件,或没有权限没有权限访问的文件相关信息;

    open_file_cache_min_uses

    Syntax: open_file_cache_min_uses number;
    Default: open_file_cache_min_uses 1;
    Context: http, server, location

    设置由open_file_cache指令的inactive参数配置的时间段内文件访问的最小数量,这是文件描述符在高速缓存中保持打开所必需的。

    open_file_cache_valid

    Syntax: open_file_cache_valid time;
    Default: open_file_cache_valid 60s;
    Context: http, server, location

    每隔多久检查一次缓存中缓存项的有效性;默认为60s;

    ngx_http_access_module模块

    ngx_http_access_module模块允许限制对某些客户端地址的访问。
    访问也可以通过密码,子请求的结果或JWT来限制。 通过地址和密码的同时访问限制由满足指令控制。

    allow

    Syntax: allow address | CIDR | unix: | all;
    Default: —
    Context: http, server, location, limit_except

    允许访问指定的网络或地址。

    deny

    Syntax: deny address | CIDR | unix: | all;
    Default: —
    Context: http, server, location, limit_except

    拒绝指定网络或地址的访问。

    ngx_http_auth_basic_module模块

    ngx_http_auth_basic_module模块允许通过使用“HTTP Basic Authentication”协议验证用户名和密码来限制对资源的访问。访问也可以由地址,子请求的结果或JWT限制。 通过地址和密码的同时访问限制由满足指令控制。

    auth_basic

    Syntax: auth_basic string | off;
    Default: auth_basic off;
    Context: http, server, location, limit_except

    启用使用“HTTP Basic Authentication”协议验证用户名和密码。 指定的参数用作领域。 参数值可以包含变量(1.3.10,1.2.7)。 特殊值off允许取消从先前配置级别继承的auth_basic指令的影响。

    auth_basic_user_file

    Syntax: auth_basic_user_file file;
    Default: —
    Context: http, server, location, limit_except

    指定验证的用户名和密码的文件,格式如下:

    # comment
    name1:password1
    name2:password2:comment
    name3:password3
    

    文件名可以包含变量。
    支持以下密码类型:

    • 用crypt() 函数加密; 可以使用来自Apache HTTP Server分发或“openssl passwd”命令的“htpasswd”实用程序生成;
    • 散列与基于MD5的密码算法(apr1)的Apache变体; 可以用相同的工具生成;
    • 由RFC 2307中描述的“{scheme} data”语法(1.0.3+)指定;

    举例

    nginx.conf:
    root /data/website;
    location /admin {
    auth_basic "Admin";
    auth_basic_user_file /data/website/admin/.admin;
    }
    # mkdir /data/website/admin -p
    # htpasswd -cm /data/website/admin/.admin bols
    # cat /data/website/admin/.admin
    bols:$apr1$dW4Pn2bj$.5SXAqXqNpp6dBN5SuMhK1
    # echo /data/website/admin/ > /data/website/admin/index.html
    # curl -u bols:bols http://www.a.com/admin/index.html
    /data/website/admin/
    # curl http://www.a.com/admin/index.html
    <html>
    <head><title>401 Authorization Required</title></head>
    <body bgcolor="white">
    <center><h1>401 Authorization Required</h1></center>
    <hr><center>nginx/1.10.1</center>
    </body>
    </html>
    

    ngx_http_stub_status_module模块

    ngx_http_stub_status_module模块提供对基本状态信息的访问。此模块不是默认构建的,应使用--with-http_stub_status_module配置参数启用。

    stub_status

    Syntax: stub_status;
    Default: —
    Context: server, location

    通过指定的uri输出stub status;在1.7.5之前的版本中,指令语法需要一个任意参数,例如,“stub_status on”。举例:

    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:处理的连接的总数。 通常,参数值与accept相同,除非已达到某些资源限制(例如,worker_connections限制)。
    • requests:客户端请求的总数。
    • Reading:nginx正在读取请求头的当前连接数。
    • Writing:nginx正在将响应写回客户端的当前连接数。
    • Waiting:等待请求的空闲客户端连接的当前数量。

    ngx_http_referer_module模块

    ngx_http_referer_module模块用于阻止对“Referer”头字段中具有无效值的请求对站点的访问。 应该记住,使用适当的“Referer”字段值来构造请求是非常容易的,因此该模块的预期目的不是彻底阻止这种请求,而是阻止普通浏览器发送的请求的大量流动。 还应该考虑到,即使对于有效的请求,常规浏览器也可能不发送“Referer”字段。

    valid_referers

    Syntax: valid_referers none | blocked | server_names | string ...;
    Default: —
    Context: server, location

    指定“Referer”请求头字段值,这将导致嵌入的$ invalid_referer变量设置为空字符串。 否则,变量将设置为“1”。 搜索匹配项不区分大小写。

    参数可以如下:

    • none:请求报文不存在referer首部;
    • blocked:请求报文中存在referer首部,但其没有有效值,或其值非以http://或https://开头;
    • server_names:“Referer”请求头字段包含服务器名称之一;
    • arbitrary string:定义服务器名称和可选的URI前缀。 服务器名称的开头或结尾可以有“*”。 在检查期间,“Referer”字段中的服务器端口被忽略;
    • regular expression:第一个符号应该是一个“〜”。 应当注意,表达式将与在“http://”或“https://”之后开始的文本匹配。

    举例:

    valid_referers none blocked server_names
                   *.example.com example.* www.example.org/galleries/
                   ~.google.;
    

    内置变量:$invalid_referer(所有不能符合valid_referer指定定义的引用请求均为不合法引用)
    举例

    nginx.conf:
    location ~* .(gif|png|jpg|bmp)$ {
    valid_referers none blockd www.a.com *.a.com;
    if ($invalid_referer){
    rewrite ^/ http://www.a.com/404.html;
    }
    }
    

    ngx_http_ssl_module模块

    ngx_http_ssl_module模块为HTTPS提供必要的支持。
    此模块不是默认构建的,应使用--with-http_ssl_module配置参数启用。此为了减少处理器负载,建议:

    • 设置工作进程数等于处理器数,
    • 启用保持活动连接,
    • 启用共享会话缓存,
    • 禁用内置会话缓存,
    • 并可能增加会话生存期(默认为5分钟):
    worker_processes auto;
    
    http {
    
        ...
    
        server {
            listen              443 ssl;
            keepalive_timeout   70;
    
            ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
            ssl_ciphers         AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
            ssl_certificate     /usr/local/nginx/conf/cert.pem;
            ssl_certificate_key /usr/local/nginx/conf/cert.key;
            ssl_session_cache   shared:SSL:10m;
            ssl_session_timeout 10m;
    
            ...
        }
    

    ssl_certificate

    Syntax: ssl_certificate file;
    Default: —
    Context: http, server

    指定具有给定虚拟服务器的PEM格式的证书的文件。 如果除了主证书之外还应该指定中间证书,则应按照以下顺序在同一文件中指定中间证书:主证书先出现,然后是中间证书。 PEM格式的秘密密钥可以放置在同一文件中。

    从版本1.11.0开始,可以多次指定此伪指令来加载不同类型的证书,例如RSA和ECDSA:

    server {
        listen              443 ssl;
        server_name         example.com;
    
        ssl_certificate     example.com.rsa.crt;
        ssl_certificate_key example.com.rsa.key;
    
        ssl_certificate     example.com.ecdsa.crt;
        ssl_certificate_key example.com.ecdsa.key;
    
        ...
    }
    

    Notes:只有OpenSSL 1.0.2或更高版本支持不同证书的单独证书链。 对于旧版本,只能使用一个证书链。
    应该记住,由于HTTPS协议的限制,虚拟服务器应该在不同的IP地址上侦听:

    server {
        listen          192.168.1.1:443;
        server_name     one.example.com;
        ssl_certificate one.example.com.crt;
        ...
    }
    
    server {
        listen          192.168.1.2:443;
        server_name     two.example.com;
        ssl_certificate two.example.com.crt;
        ...
    }
    

    否则将为第二个站点发出第一个服务器的证书。

    ssl_certificate_key

    Syntax: ssl_certificate_key file;
    Default: —
    Context: http, server

    指定具有给定虚拟服务器的PEM格式的密钥的文件。
    可以指定值engine:name:id而不是文件(1.7.9),该文件从OpenSSL引擎名称加载具有指定标识的密钥。

    ssl_ciphers

    Syntax: ssl_ciphers ciphers;
    Default: ssl_ciphers HIGH:!aNULL:!MD5;
    Context: http, server

    指定启用的密码。 密码以OpenSSL库理解的格式指定,例如:

    ssl_ciphers ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    

    可以使用“openssl ciphers”命令查看完整列表。
    以前的nginx版本默认使用不同的密码。

    ssl_protocols

    Syntax: ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
    Default: ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    Context: http, server

    启用指定的协议。 仅当使用版本1.0.1或更高版本的OpenSSL库时,TLSv1.1和TLSv1.2参数才起作用。
    Notes:从版本1.1.13和1.0.12开始支持TLSv1.1和TLSv1.2参数,因此,当旧版nginx版本使用OpenSSL版本1.0.1或更高版本时,这些协议可以正常工作,但不能禁用。

    ssl_session_cache

    Syntax: ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
    Default: ssl_session_cache none;
    Context: http, server

    设置存储会话参数的高速缓存的类型和大小。 缓存可以是以下任何类型:

    • off:严格禁止使用会话缓存:nginx显式告诉客户端会话可能不会被重用。
    • none:缓慢地禁止使用会话缓存:nginx告诉客户端会话可以被重用,但实际上不在高速缓存中存储会话参数。
    • builtin:一个内置在OpenSSL中的缓存; 仅由一个工作进程使用。 缓存大小在会话中指定。 如果未指定大小,则等于20480个会话。 使用内置缓存可能会导致内存碎片。
    • shared:在所有工作进程之间共享的高速缓存。 缓存大小以字节为单位指定; 一兆字节可以存储约4000个会话。 每个共享缓存应该有一个任意名称。 具有相同名称的缓存可用于多个虚拟服务器。

    两种缓存类型可以同时使用,例如:

    ssl_session_cache builtin:1000 shared:SSL:10m;
    

    但是只使用没有内置缓存的共享缓存应该更有效。

    ssl_session_timeout

    Syntax: ssl_session_timeout time;
    Default: ssl_session_timeout 5m;
    Context: http, server

    指定客户端可以重用会话参数的时间。

    举例

    # cd /etc/pki/CA/private/
    # (umask 077; openssl genrsa 2048 > cakey.pem)
    # cd ..
    # openssl req -new -x509 -key ./private/cakey.pem -out cacert.pem
    # cd /etc/nginx/ssl/
    # (umask 077; openssl genrsa 1024 > nginx.key)
    #  openssl req -new -key nginx.key -out nginx.csr
    # openssl ca -in nginx.csr -out nginx.crt -days 3650
    Using configuration from /etc/pki/tls/openssl.cnf
    Check that the request matches the signature
    Signature ok
    Certificate Details:
            Serial Number: 1 (0x1)
            Validity
                Not Before: Feb 18 15:20:44 2017 GMT
                Not After : Feb 16 15:20:44 2027 GMT
            Subject:
                countryName               = CN
                stateOrProvinceName       = ShangHai
                organizationName          = ShangHai
                organizationalUnitName    = study
                commonName                = ssl.study.com
                emailAddress              = admin@study.com
            X509v3 extensions:
                X509v3 Basic Constraints: 
                    CA:FALSE
                Netscape Comment: 
                    OpenSSL Generated Certificate
                X509v3 Subject Key Identifier: 
                    24:B9:52:AE:21:6F:DC:54:D3:8E:22:B3:AC:5A:46:38:EC:80:A3:A2
                X509v3 Authority Key Identifier: 
                    keyid:69:2B:ED:99:D9:BB:DE:D6:2C:F5:B4:11:D8:A3:12:A7:D5:3D:F7:2A
    
    Certificate is to be certified until Feb 16 15:20:44 2027 GMT (3650 days)
    Sign the certificate? [y/n]:y
    
    
    1 out of 1 certificate requests certified, commit? [y/n]y
    Write out database with 1 new entries
    Data Base Updated
    # cat /etc/pki/CA/serial
    02
    # cat /etc/pki/CA/index.txt
    V	270216152044Z		01	unknown	/C=CN/ST=ShangHai/O=ShangHai/OU=study/CN=ssl.study.com/emailAddress=admin@study.com
    # vim nginx.conf
        server {
            listen       443 ssl;
            server_name  ssl.study.com;
    
            ssl_certificate      /etc/nginx/ssl/nginx.crt;
            ssl_certificate_key  /etc/nginx/ssl/nginx.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;
            }
        }
    # nginx 
    # curl --cacert /etc/pki/CA/cacert.pem -I https://ssl.study.com
    HTTP/1.1 200 OK
    Server: nginx/1.10.1
    Date: Sat, 18 Feb 2017 15:48:10 GMT
    Content-Type: text/html
    Content-Length: 3700
    Last-Modified: Sat, 02 Jul 2016 19:41:19 GMT
    Connection: keep-alive
    ETag: "577818df-e74"
    Accept-Ranges: bytes
    

    注意
    在自签nginx的证书是的时候遇到了下面的问题:

    # openssl ca -in /etc/nginx/ssl/nginx.csr -out /etc/nginx/ssl/nginx.crt -days 3650
    Using configuration from /etc/pki/tls/openssl.cnf
    Check that the request matches the signature
    Signature ok
    The organizationName field needed to be the same in the
    CA certificate (example) and the request (study)
    

    解决方法是:

    # vim /etc/pki/tls/openssl.cnf
    #string_mask = utf8only
    string_mask = pkix
    

    我是修改ssl的配置文件才弄好的。
    详细参考

    ngx_http_log_module模块

    ngx_http_log_module模块以指定的格式写入请求日志。
    请求记录在处理结束的位置的上下文中。 如果在请求处理期间发生内部重定向,则它可能与原始位置不同。

    access_log

    Syntax: access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
    access_log off;
    Default: access_log logs/access.log combined;
    Context: http, server, location, if in location, limit_except

    设置缓冲日志写入的路径,格式和配置。可以在同一级别上指定多个日志。可以通过在第一个参数中指定“syslog:”前缀来配置日志记录到syslog。特殊值off取消当前级别上的所有access_log指令。如果未指定格式,则使用预定义的“组合”格式。
    如果使用buffer或gzip(1.3.10,1.2.7)参数,将对日志的写入使用buffer。
    Notes:缓冲区大小不能超过对磁盘文件的原子写入大小。
    详细参考

    log_format

    Syntax: log_format name [escape=default|json] string ...;
    Default: log_format combined "...";
    Context: http

    指定日志格式。
    escape参数(1.11.8)允许在变量中设置json或默认字符转义,默认情况下使用默认转义。
    日志格式可以包含公共变量和仅在写日志时存在的变量:

    • $ bytes_sent:发送给客户端的字节数
    • $connection:连接序列号
    • $ connection_requests:通过连接发出的请求的当前数量(1.1.18)
    • $ msec:时间(以秒为单位),在日志写入时具有毫秒分辨率
    • $ pipe:“p”如果请求是流水线的,“.”否则
    • $ request_length:请求长度(包括请求行,头和请求体)
    • $ request_time:请求处理时间(以秒为单位,以毫秒为单位); 从客户端读取第一个字节之间经过的时间,并将最后一个字节后的日志写入发送到客户端
    • $ status:响应状态
    • $ time_iso8601:本地时间采用ISO 8601标准格式
    • $ time_local:公共日志格式中的本地时间

    open_log_file_cache

    Syntax: open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time];
    open_log_file_cache off;
    Default: open_log_file_cache off;
    Context: http, server, location

    定义一个缓存,用于存储其名称包含变量的常用日志的文件描述符。 该伪指令具有以下参数:

    • max:设置高速缓存中的描述符的最大数量; 如果缓存变满,则关闭最近最少使用(LRU)描述符
    • inactive:设置如果在此时间期间没有访问则缓存的描述符被关闭的时间; 默认为10秒
    • min_uses:设置由inactive参数定义的时间内文件使用的最小数量,以使描述符在缓存中保持打开; 默认为1
    • valid:设置时间,在此之后应检查文件是否仍以相同名称存在; 默认为60秒
    • off:禁用缓存

    ngx_http_rewrite_module

    ngx_http_rewrite_module模块用于使用PCRE正则表达式更改请求URI,返回重定向并有条件地选择配置。
    ngx_http_rewrite_module模块伪指令按以下顺序处理:
    在服务器级别上指定的此模块的指令顺序执行;
    反复:

    • 基于请求URI搜索位置;
    • 在所找到的位置内指定的该模块的指令被顺序地执行;
    • 如果请求URI被重写,则循环被重复,但不超过10次。

    break

    Syntax: break;
    Default: —
    Context: server, location, if

    停止处理当前的ngx_http_rewrite_module伪指令集。
    如果在位置内指定了指令,则在该位置继续进行请求的进一步处理。

    if

    Syntax: if (condition) { ... }
    Default: —
    Context: server, location

    评估指定的条件。 如果为true,那么在大括号中指定的模块指令将被执行,并且请求被分配在if指令内部的配置。 if指令内的配置继承自先前的配置级别。
    条件可以是以下任何一种:

    • 变量名;如果变量的值为空字符串或“0”,则为false;
    • 在版本1.0.1之前,以“0”开头的任何字符串被视为false值。
    • 使用“=”和“!=”运算符将变量与字符串进行比较;
    • ~:模式匹配,区分字符大小写;~*:模式匹配,不区分字符大小写;!~:模式不匹配,区分字符大小写;!~*: 模式不匹配,不区分字符大小写;
    • 使用“-f”和“!-f”运算符检查文件存在;
    • 使用“-d”和“!-d”运算符检查目录存在;
    • 使用“-e”和“!-e”运算符检查文件,目录或符号链接是否存在;
    • 使用“-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;
    }
    

    $ invalid_referer嵌入式变量的值由valid_referers指令设置。

    return

    Syntax: return code [text];
    return code URL;
    return URL;
    Default: —
    Context: server, location, if

    停止处理并将指定的代码返回给客户端。 非标准代码444关闭连接而不发送响应报头。
    从版本0.8.42开始,可以指定重定向URL(代码301,302,303和307)或响应正文文本(对于其他代码)。 响应正文文本和重定向网址可以包含变量。 作为特殊情况,可以将重定向URL指定为此服务器的本地URI,在这种情况下,根据请求方案($ scheme)和server_name_in_redirect和port_in_redirect伪指令形成完全重定向URL。
    此外,可以将用于利用代码302的临时重定向的URL指定为唯一的参数。 此类参数应以“http://”,“https://”或“$ scheme”字符串开头。 URL可以包含变量。

    rewrite

    Syntax: rewrite regex replacement [flag];
    Default: —
    Context: server, location, if

    如果指定的正则表达式匹配请求URI,那么将按照替换字符串中指定的方式更改URI。 重写指令按照它们在配置文件中的出现顺序执行。 可以使用标志来终止指令的进一步处理。 如果替换字符串以“http://”,“https://”或“$ scheme”开头,则处理停止,并将重定向返回给客户端。
    可选的标志参数可以是下列之一:

    • last:停止处理当前的ngx_http_rewrite_module指令集,并开始搜索与更改的URI匹配的新位置;
    • break:停止处理当前的ngx_http_rewrite_module指令集,如同break指令一样;
    • redirect:返回具有302代码的临时重定向; 如果替换字符串不以“http://”,“https://”或“$ scheme”开头,则使用;
    • permanent:返回301代码的永久重定向。

    完全重定向URL根据请求方案($ scheme)和server_name_in_redirect和port_in_redirect伪指令形成。
    例:

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

    但是,如果这些指令放在“/ download /”位置,最后一个标志应该被替换,否则nginx将使10个周期并返回500错误:

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

    如果替换字符串包括新的请求参数,则在它们之后附加先前的请求参数。 如果这是不希望的,则在替换字符串的末尾放置一个问号,避免附加它们,例如:

    rewrite ^/users/(.*)$ /show?user=$1? last;
    

    如果正则表达式包含“}”或“;”字符,则整个表达式应用单引号或双引号括起来。
    举例

    nginx.conf:
            location / {
                root   html;
                index  index.html index.htm;
                rewrite (.*).txt $1.html;
            }
    # cat /usr/share/nginx/html/test.html 
    test.html
    # curl   https://ssl.study.com/test.txt
    test.html
    

    如果出现死循环则会报500错误:

    nginx.conf:
            location / {
                root   html;
                index  index.html index.htm;
                rewrite (.*).txt $1.html;
            }
           location ~* .html$ {
            root html;
            index index.html;
            rewrite (.*).html $1.txt;
           }
    # curl  -I  https://ssl.study.com/test.txt
    HTTP/1.1 500 Internal Server Error
    Server: nginx/1.10.1
    Date: Sat, 18 Feb 2017 16:29:41 GMT
    Content-Type: text/html
    Content-Length: 193
    Connection: close
    

    rewrite_log

    Syntax: rewrite_log on | off;
    Default: rewrite_log off;
    Context: http, server, location, if

    启用或禁用将ngx_http_rewrite_module模块伪指令的处理结果记录到通知级别的error_log。

    set

    Syntax: set $variable value;
    Default: —
    Context: server, location, if

    设置指定变量的值。 该值可以包含文本,变量及其组合。

    ngx_http_gzip_module

    ngx_http_gzip_module模块是一个使用“gzip”方法压缩响应的过滤器。 这通常有助于将传输数据的大小减少一半或更多。

    gzip

    Syntax: gzip on | off;
    Default: gzip off;
    Context: http, server, location, if in location

    启用或停用响应的压缩。

    gzip_comp_level

    Syntax: gzip_comp_level level;
    Default: gzip_comp_level 1;
    Context: http, server, location

    设置响应的gzip压缩级别。 可接受的值介于1到9之间。

    gzip_disable

    Syntax: gzip_disable regex ...;
    Default: —
    Context: http, server, location
    This directive appeared in version 0.6.23.

    禁用对“User-Agent”标头字段与任何指定的正则表达式匹配的请求的响应进行gzipping。

    gzip_min_length

    Syntax: gzip_min_length length;
    Default: gzip_min_length 20;
    Context: http, server, location

    设置将被gzip压缩的响应的最小长度。 长度仅根据“Content-Length”响应头字段确定。

    gzip_http_version

    Syntax: gzip_http_version 1.0 | 1.1;
    Default: gzip_http_version 1.1;
    Context: http, server, location

    设置压缩响应所需的请求的最小HTTP版本。

    gzip_proxied

    Syntax: gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...;
    Default: gzip_proxied off;
    Context: http, server, location

    根据请求和响应启用或禁用代理请求的响应的gzipping。 请求被代理的事实由“Via”请求头字段的存在来确定。 该伪指令接受多个参数:

    • off:禁用所有代理请求的压缩,忽略其他参数;
    • expired:如果响应头包括具有禁用缓存的值的“Expires”字段,则启用压缩;
    • no-cache:如果响应头包括具有“no-cache”参数的“Cache-Control”字段,则启用压缩;
    • no-store:如果响应头包括具有“no-store”参数的“Cache-Control”字段,则启用压缩;
    • private:如果响应头包括具有“private”参数的“Cache-Control”字段,则启用压缩;
    • no_last_modified:如果响应头不包括“Last-Modified”字段,则启用压缩;
    • no_etag:如果响应报头不包括“ETag”字段,则启用压缩;
    • auth:如果请求头包括“授权”字段则启用压缩;
    • any:启用对所有代理请求的压缩。

    gzip_types

    Syntax: gzip_types mime-type ...;
    Default: gzip_types text/html;
    Context: http, server, location

    除了“text / html”之外,还允许为指定的MIME类型应用“gzipping”响应。 特殊值“*”匹配任何MIME类型(0.8.29)。 对“text / html”类型的响应总是压缩。

    gzip_vary

    Syntax: gzip_vary on | off;
    Default: gzip_vary off;
    Context: http, server, location

    如果指令gzip,gzip_static或gunzip处于活动状态,则启用或禁用插入“Vary:Accept-Encoding”响应头字段。

    ngx_http_fastcgi_module

    ngx_http_fastcgi_module模块允许将请求传递到FastCGI服务器。

    fastcgi_pass

    Syntax: fastcgi_pass address;
    Default: —
    Context: location, if in location

    设置FastCGI服务器的地址。 地址可以指定为域名或IP地址和端口:

    fastcgi_pass localhost:9000;
    

    如果域名解析为多个地址,则所有这些地址都将以循环方式使用。 此外,可以将地址指定为服务器组。

    fastcgi_index

    Syntax: fastcgi_index name;
    Default: —
    Context: http, server, location

    在$ fastcgi_script_name变量的值中设置将附加在以斜杠结尾的URI后面的文件名。 例如,使用这些设置和“/page.php”请求,SCRIPT_FILENAME参数将等于“/home/www/scripts/php/page.php”,对于“/”请求,它将等于“/ home / www / scripts / php / index.php“。

    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
    

    fastcgi_param

    Syntax: fastcgi_param parameter value [if_not_empty];
    Default: —
    Context: http, server, location

    设置应传递到FastCGI服务器的参数。 该值可以包含文本,变量及其组合。 当且仅当没有在当前级别上定义fastcgi_param伪指令时,这些伪指令才继承自上一级。
    以下示例显示了PHP的最低要求设置:

    fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
    fastcgi_param QUERY_STRING    $query_string;
    

    SCRIPT_FILENAME参数在PHP中用于确定脚本名称,并且QUERY_STRING参数用于传递请求参数。
    对于处理POST请求的脚本,还需要以下三个参数:

    fastcgi_param REQUEST_METHOD  $request_method;
    fastcgi_param CONTENT_TYPE    $content_type;
    fastcgi_param CONTENT_LENGTH  $content_length;
    

    如果PHP是使用--enable-force-cgi-redirect配置参数构建的,那么REDIRECT_STATUS参数也应该使用值“200”传递:

    fastcgi_param REDIRECT_STATUS 200;
    

    如果指令使用if_not_empty(1.1.11)指定,那么这样的参数不会传递到服务器,直到它的值不为空:

    fastcgi_param HTTPS           $https if_not_empty;
    

    fastcgi_cache_path

    Syntax: 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];
    Default: —
    Context: http

    设置缓存的路径和其他参数。 缓存数据存储在文件中。 高速缓存中的密钥和文件名都是将MD5函数应用于代理URL的结果。 levels参数定义缓存的层次结构级别:从1到3,每个级别接受值1或2.例如,在以下配置中:

    fastcgi_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;
    

    缓存中的文件名将如下所示:

    /data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c
    

    详细参考

    fastcgi_cache

    Syntax: fastcgi_cache zone | off;
    Default: fastcgi_cache off;
    Context: http, server, location

    定义用于缓存的共享内存区域。 同一区域可以在几个地方使用。 参数值可以包含变量(1.7.9)。 off参数禁用从先前配置级别继承的缓存。

    fastcgi_cache_key

    Syntax: fastcgi_cache_key string;
    Default: —
    Context: http, server, location

    定义用于缓存的键。

    fastcgi_cache_methods

    Syntax: fastcgi_cache_methods GET | HEAD | POST ...;
    Default: fastcgi_cache_methods GET HEAD;
    Context: http, server, location
    This directive appeared in version 0.7.59.

    如果客户端请求方法列在此指令中,那么响应将被缓存。 “GET”和“HEAD”方法总是添加到列表中,但建议明确指定它们。 另请参见fastcgi_no_cache指令。

    fastcgi_cache_min_uses

    Syntax: fastcgi_cache_min_uses number;
    Default: fastcgi_cache_min_uses 1;
    Context: http, server, location

    设置在其后响应将被缓存的请求数。

    fastcgi_cache_use_stale

    Syntax: fastcgi_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_503 | http_403 | http_404 | off ...;
    Default:
    fastcgi_cache_use_stale off;
    Context: http, server, location

    确定在与FastCGI服务器通信期间发生错误时,可以使用过时缓存响应的情况。 指令的参数与fastcgi_next_upstream指令的参数匹配。
    如果无法选择处理请求的FastCGI服务器,则错误参数还允许使用陈旧的缓存响应。
    此外,如果更新参数当前正在被更新,则允许使用陈旧的缓存响应。 这允许在更新缓存数据时最大限度地减少对FastCGI服务器的访问次数。
    要在填充新缓存元素时最大限度地减少对FastCGI服务器的访问次数,可以使用fastcgi_cache_lock指令。

    fastcgi_cache_valid

    Syntax: fastcgi_cache_valid [code ...] time;
    Default: —
    Context: http, server, location

    设置不同响应代码的缓存时间。 例如,以下指令:

    fastcgi_cache_valid 200 302 10m;
    fastcgi_cache_valid 404      1m;
    

    对代码200和302的响应设置10分钟的缓存,对代码404的响应设置为1分钟。
    如果仅指定高速缓存时间:

    fastcgi_cache_valid 5m;
    

    那么只缓存200,301和302响应。
    此外,可以指定any参数来缓存任何响应:

    fastcgi_cache_valid 200 302 10m;
    fastcgi_cache_valid 301      1h;
    fastcgi_cache_valid any      1m;
    

    缓存的参数也可以直接在响应头中设置。 这比使用指令设置缓存时间具有更高的优先级。

    • “X-Accel-Expires”标头字段设置响应的缓存时间(以秒为单位)。 零值禁用缓存用于响应。 如果值以@前缀开头,则它设置自Epoch开始的绝对时间(以秒为单位),直到响应可以被缓存。
    • 如果报头不包括“X-Accel-Expires”字段,则可以在报头字段“Expires”或“Cache-Control”中设置高速缓存的参数。
    • 如果头包括“Set-Cookie”字段,则这样的响应将不被缓存。
    • 如果头包括具有特殊值“*”的“Vary”字段,则这样的响应将不被缓存(1.7.7)。 如果头部包括具有另一个值的“Vary”字段,则这样的响应将被缓存,考虑相应的请求头字段(1.7.7)。

    可以使用fastcgi_ignore_headers指令禁用对这些响应头字段中的一个或多个的处理。

    注意:调用缓存时,至少应该指定三个参数:fastcgi_cache、fastcgi_cache_key、fastcgi_cache_valid。
    举例

    nginx.conf:
    http {
        include       mime.types;
        default_type  application/octet-stream;
    	sendfile        on;
    	keepalive_timeout  65;
    	fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fcgicache:10m;
    	server {
            listen       80;
            server_name  www.a.com;
    		location / {
    		root html;
    		index  index.html index.htm;
    		}
            location ~ .php$ {
                root           html;
                fastcgi_pass   127.0.0.1:9000;
                fastcgi_cache  fcgicache;
                fastcgi_cache_key $request_uri;
                fastcgi_cache_valid 200 302 10m;
                fastcgi_cache_valid 301      1h;
                fastcgi_cache_valid any      1m;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html/$fastcgi_script_name;
                include        fastcgi_params;
            }
        }
    }
    没有启用缓存的测试:
    # ab -c 100 -n 1000 http://www.a.com/info.php
    ···
    Requests per second:    1299.63 [#/sec] (mean)
    Time per request:       76.945 [ms] (mean)
    Time per request:       0.769 [ms] (mean, across all concurrent requests)
    Transfer rate:          48288.03 [Kbytes/sec] received
    ···
    启用缓存的测试:
    # ab -c 100 -n 1000 http://www.a.com/info.php
    ...
    Requests per second:    7686.87 [#/sec] (mean)
    Time per request:       13.009 [ms] (mean)
    Time per request:       0.130 [ms] (mean, across all concurrent requests)
    Transfer rate:          285607.67 [Kbytes/sec] received
    ...
    

    注意

    • 创建缓存最少需要定义四个指令:fastcgi_cache_path、fastcgi_cache_key、fastcgi_cache_valid、fastcgi_cache。
    • 缓存定义的目录需要手动创建。

    ngx_http_proxy_module

    ngx_http_proxy_module模块允许将请求传递到另一个服务器。

    proxy_pass

    Syntax: proxy_pass URL;
    Default: —
    Context: location, if in location, limit_except

    设置代理服务器的协议和地址以及应映射位置的可选URI。 作为协议,可以指定“http”或“https”。
    proxy_pass后面的路径不带uri时,其会将location的uri传递给后端的主机;下面的示例会将/uri/传递给backend服务器;

    location  /uri/ {
    	proxy_pass http://hostname;
    }
    

    proxy_pass后面的路径是一个uri时,其会将location的uri替换为后端主机自己的uri;

    location  /uri/ {
    	proxy_pass http://hostname/new_uri/;
    }
    

    如果location定义其uri时使用的正则表达式模式匹配,则proxy_pass后的路径不能够使用uri;

    location  ~*  .(jpg|gif|jpeg)$  {
    	proxy_pass  http://HOSTNAME;
    }
    

    此处的http://HOSTNAME后面不能有任何uri,哪怕只有/也不可以;

    举例

    nginx.conf:
    location / {
    proxy_pass http://192.168.0.201;
    index  index.html index.htm;
    }
    # curl http://www.a.com/bbs/index.html
    192.160.0.201:bbs
    # curl http://www.a.com/
    192.169.0.201
    
    nginx.conf:
    location /bbs {
    proxy_pass http://192.168.0.201;
    index  index.html index.htm;
    }
    # curl http://www.a.com/test.html
    192.168.0.220
    # curl http://www.a.com/bbs/index.html
    192.160.0.201:bbs
    
    nginx.conf:
    location /bbs {
    proxy_pass http://192.168.0.201/;
    index  index.html index.htm;
    }
    # curl http://www.a.com/bbs/index.html
    192.169.0.201
    # curl http://www.a.com/test.html
    192.168.0.220
    
    nginx.conf:
    location / {
    proxy_pass http://192.168.0.201/bbs/;
    index  index.html index.htm;
    }
    # curl http://www.a.com/index.html
    192.160.0.201:bbs
    # curl http://www.a.com/bbs/index.html
    <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    <html><head>
    <title>404 Not Found</title>
    </head><body>
    <h1>Not Found</h1>
    <p>The requested URL /bbs/bbs/index.html was not found on this server.</p>
    <hr>
    <address>Apache/2.2.15 (CentOS) Server at 192.168.0.201 Port 80</address>
    </body></html>
    

    proxy_set_header

    Syntax: proxy_set_header field value;
    Default: proxy_set_header Host $proxy_host;
    proxy_set_header Connection close;
    Context: http, server, location

    用于proxy server向backend server发请求报文时,将某请求首部重新赋值,或在原有值后面添加一个新的值; 也可以添加自定义首部;
    举例:

    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
    

    原有请求报文中如果存在X-Forwared-For首部,则将remote_addr以逗号分隔补原有值后,否则则直接添加此首部;

    proxy_cache_path

    Syntax: 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];
    Default: —
    Context: http

    设置缓存的路径和其他参数。 缓存数据存储在文件中。 高速缓存中的文件名是将MD5函数应用于高速缓存密钥的结果。 levels参数定义缓存的层次结构级别:从1到3,每个级别接受值1或2.

    proxy_cache

    Syntax: proxy_cache zone | off;
    Default: proxy_cache off;
    Context: http, server, location

    定义用于缓存的共享内存区域。 同一区域可以在几个地方使用。 参数值可以包含变量(1.7.9)。 off参数禁用从先前配置级别继承的缓存。

    proxy_cache_key

    Syntax: proxy_cache_key string;
    Default: proxy_cache_key $scheme$proxy_host$request_uri;
    Context: http, server, location

    例如,定义用于缓存的键:

    proxy_cache_key "$host$request_uri $cookie_user";
    

    默认情况下,指令的值接近字符串:

    proxy_cache_key $scheme$proxy_host$uri$is_args$args;
    

    proxy_cache_valid

    Syntax: proxy_cache_valid [code ...] time;
    Default: —
    Context: http, server, location

    设置不同响应代码的缓存时间。
    例如,以下指令:

    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404      1m;
    

    对代码200和302的响应设置10分钟的缓存,对代码404的响应设置为1分钟。
    如果仅指定高速缓存时间:

    proxy_cache_valid 5m;
    

    那么只缓存200,301和302响应。
    此外,可以指定any参数来缓存任何响应:

    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 301      1h;
    proxy_cache_valid any      1m;
    

    缓存的参数也可以直接在响应头中设置。 这比使用指令设置缓存时间具有更高的优先级。

    • “X-Accel-Expires”标头字段设置响应的缓存时间(以秒为单位)。 零值禁用缓存用于响应。 如果值以@前缀开头,它将设置从Epoch开始的绝对时间(以秒为单位),直到响应可以被缓存。
    • 如果报头不包括“X-Accel-Expires”字段,则可以在报头字段“Expires”或“Cache-Control”中设置高速缓存的参数。
    • 如果头包括“Set-Cookie”字段,则这样的响应将不被缓存。
    • 如果头包括具有特殊值“*”的“Vary”字段,则这样的响应将不被缓存(1.7.7)。 如果头部包括具有另一个值的“Vary”字段,则这样的响应将在考虑相应的请求头字段(1.7.7)的情况下被缓存。

    可以使用proxy_ignore_headers指令禁用对这些响应头字段中的一个或多个的处理。
    举例

    nginx.conf:
    proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=proxycache:10m;
    location / {
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 301      1h;
    proxy_cache_valid any      1m;
    proxy_pass http://192.168.0.201/bbs/;
    index  index.html index.htm;
    }
    中间重新载入配置在访问页面进行缓存。
    # ll /var/cache/nginx/proxy/
    总用量 0
    drwx------ 4 nginx nginx 24 2月  20 00:12 9
    

    proxy_connect_timeout

    Syntax: proxy_connect_timeout time;
    Default: proxy_connect_timeout 60s;
    Context: http, server, location

    定义与代理服务器建立连接的超时。 应该注意,该超时通常不能超过75秒。

    proxy_send_timeout

    Syntax: proxy_send_timeout time;
    Default: proxy_send_timeout 60s;
    Context: http, server, location

    设置将请求传输到代理服务器的超时。 超时仅在两个连续的写操作之间设置,而不是用于传输整个请求。 如果代理服务器在此时间内未收到任何内容,则连接将关闭。

    proxy_read_timeout

    Syntax: proxy_read_timeout time;
    Default: proxy_read_timeout 60s;
    Context: http, server, location

    定义从代理服务器读取响应的超时。 超时仅在两个连续读取操作之间设置,而不是用于传输整个响应。 如果代理服务器在此时间内未发送任何内容,则连接将关闭。

    ngx_http_headers_module

    ngx_http_headers_module模块允许将“Expires”和“Cache-Control”报头字段和任意字段添加到响应标头。

    add_header

    Syntax: add_header name value [always];
    Default: —
    Context: http, server, location, if in location

    如果响应代码等于200,201,204,206,301,302,303,304或307,则将指定的字段添加到响应头中。值可以包含变量。
    如果指定了always参数(1.7.5),则将添加头字段,而不考虑响应代码。
    举例

    # curl -I http://www.a.com/
    HTTP/1.1 200 OK
    Server: nginx/1.10.1
    Date: Sun, 19 Feb 2017 16:30:50 GMT
    Content-Type: text/html; charset=UTF-8
    Content-Length: 18
    Connection: keep-alive
    Last-Modified: Sun, 19 Feb 2017 15:30:24 GMT
    ETag: "2ae7-12-548e3d35ee7fc"
    Accept-Ranges: bytes
    nginx.conf:
    location / {
    add_header X-Via $server_addr;
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 301      1h;
    proxy_cache_valid any      1m;
    proxy_pass http://192.168.0.201/bbs/;
    index  index.html index.htm;
    }
    重新载入配置:
    # curl -I http://www.a.com/
    HTTP/1.1 200 OK
    Server: nginx/1.10.1
    Date: Sun, 19 Feb 2017 16:31:08 GMT
    Content-Type: text/html; charset=UTF-8
    Content-Length: 18
    Connection: keep-alive
    Last-Modified: Sun, 19 Feb 2017 15:30:24 GMT
    ETag: "2ae7-12-548e3d35ee7fc"
    X-Via: 192.168.0.220
    Accept-Ranges: bytes
    
    nginx.conf:
        proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=proxycache:10m;
       upstream webserver {
       server 192.168.0.201:80 weight=1;
       server 192.168.0.202:80 weight=1;
       hash $request_uri;
       }
        server {
            listen       80;
            server_name  www.a.com;
    location / {
    add_header X-Cache $upstream_cache_status;
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 301      1h;
    proxy_cache_valid any      1m;
    index  index.html index.htm;
    proxy_pass http://webserver;
    }
    ......
    }
    # curl http://www.a.com -I
    HTTP/1.1 200 OK
    Server: nginx/1.10.1
    Date: Sun, 19 Feb 2017 17:09:36 GMT
    Content-Type: text/html; charset=UTF-8
    Content-Length: 14
    Connection: keep-alive
    Last-Modified: Sun, 19 Feb 2017 13:16:32 GMT
    ETag: "c1600-e-548e1f49fa343"
    X-Cache: MISS
    Accept-Ranges: bytes
    # curl http://www.a.com -I
    HTTP/1.1 200 OK
    Server: nginx/1.10.1
    Date: Sun, 19 Feb 2017 17:09:37 GMT
    Content-Type: text/html; charset=UTF-8
    Content-Length: 14
    Connection: keep-alive
    Last-Modified: Sun, 19 Feb 2017 13:16:32 GMT
    ETag: "c1600-e-548e1f49fa343"
    X-Cache: HIT
    Accept-Ranges: bytes
    

    expires

    Syntax: expires [modified] time;
    expires epoch | max | off;
    Default: expires off;
    Context: http, server, location, if in location

    如果响应代码等于200,201,204,206,301,302,303,304或307,则启用或禁用添加或修改“Expires”和“Cache-Control”响应头字段。参数可以是正值 或负时间。

    ngx_http_upstream_module

    ngx_http_upstream_module模块用于定义可由proxy_pass,fastcgi_pass,uwsgi_pass,scgi_pass和memcached_pass指令引用的服务器组。

    upstream

    Syntax: upstream name { ... }
    Default: —
    Context: http

    定义一组服务器。 服务器可以在不同的端口上侦听。 此外,监听TCP和UNIX域套接字的服务器可以混合。
    举例:

    upstream backend {
        server backend1.example.com weight=5;
        server 127.0.0.1:8080       max_fails=3 fail_timeout=30s;
        server unix:/tmp/backend3;
        server backup1.example.com  backup;
    }
    

    默认情况下,请求在服务器之间使用加权循环平衡方法分发。 在上面的例子中,每个7个请求将被分配如下:5个请求到backend1.example.com,一个请求到每个第二和第三个服务器。 如果在与服务器通信期间发生错误,请求将传递到下一个服务器,依此类推,直到所有正在运行的服务器都将被尝试。 如果无法从任何服务器获得成功的响应,则客户端将接收与最后一个服务器的通信结果。

    server

    Syntax: server address [parameters];
    Default: —
    Context: upstream

    定义服务器的地址和其他参数。 可以将地址指定为域名或IP地址,具有可选端口或作为在“unix:”前缀后指定的UNIX域套接字路径。 如果未指定端口,则使用端口80。 解析为多个IP地址的域名会一次定义多个服务器。

    常用参数

    • weight=number:定义服务器权重,默认为1;
    • max_fails=number:最大失败连接尝试次数,失败连接超时时长由fail_timeout参数指定;
    • fail_timeout=number:等待目标服务器发送响应的时长;
    • backup:备用服务器,所有主服务器均故障时才启用此主机;
    • down:手动标记其不再处理任何用户请求;

    举例

    nginx.conf:
       upstream webserver {
       server 192.168.0.201:80 weight=1;
       server 192.168.0.202:80 weight=1;
       }
    
        server {
            listen       80;
            server_name  www.a.com;
    location / {
    index  index.html index.htm;
    proxy_pass http://webserver;
    }
    ......
    }
    # curl http://www.a.com
    192.169.0.201
    # curl http://www.a.com
    192.168.0.202
    

    ip_hash

    Syntax: ip_hash;
    Default: —
    Context: upstream

    指定组应使用负载平衡方法,其中请求根据客户端IP地址分布在服务器之间。 客户端IPv4地址的前三个八位字节或整个IPv6地址用作散列密钥。 该方法确保来自同一客户端的请求将始终传递到同一服务器,除非此服务器不可用。 在后一种情况下,客户端请求将被传递到另一个服务器。 最可能的是,它将始终是相同的服务器。
    从版本1.3.2和1.2.2开始支持IPv6地址。
    如果其中一个服务器需要临时删除,则应使用down参数标记,以保留客户端IP地址的当前散列。

    例:

    upstream backend {
        ip_hash;
        server backend1.example.com;
        server backend2.example.com;
        server backend3.example.com down;
        server backend4.example.com;
    }
    

    在版本1.3.1和1.2.2之前,无法使用ip_hash负载平衡方法为服务器指定权重。

    least_conn

    Syntax: least_conn;
    Default: —
    Context: upstream
    This directive appeared in versions 1.3.1 and 1.2.2.

    指定组应使用负载平衡方法,其中将请求传递到具有最少活动连接数的服务器,同时考虑服务器的权重。 如果有几个这样的服务器,则使用加权循环平衡方法依次尝试它们。

    health_check

    Syntax: health_check [parameters];
    Default: —
    Context: location

    启用周围位置中引用的组中的服务器的定期运行状况检查。此指令可作为我们商业订阅的一部分。

    常用参数

    • interval=time检测的频率,默认为5秒;
    • fails=number:判定服务器不可用的失败检测次数;默认为1次;
    • passes=number:判定服务器可用的失败检测次数;默认为1次;
    • uri=uri:做健康状态检测测试的目标uri;默认为/;
    • match=NAME:健康状态检测的结果评估调用此处指定的match配置块;

    match

    Syntax: match name { ... }
    Default: —
    Context: http

    定义用于验证对健康检查请求的响应的命名测试集。
    此指令可作为我们商业订阅的一部分。

    hash

    Syntax: hash key [consistent];
    Default: —
    Context: upstream
    This directive appeared in version 1.7.2.

    指明基于hash方式进行调度时,其hash key;hash $remote_addr相当于ip_hash;
    常用的hash key:

    • $cookie_name:将一个用户的请求始终发往同一个backend server,能实现会话绑定的功能;此处的name为cookie某些参数的名称,此处常用的有cookie_username;
    • $request_uri: 将对同一个uri的请求始终发往同一个backend server,后端为cache server时特别有用;

    keepalive

    Syntax: keepalive connections;
    Default: —
    Context: upstream
    This directive appeared in version 1.1.4.

    激活与上游服务器的连接的缓存。
    connections参数设置保存在每个工作进程的缓存中的上游服务器的空闲keepalive连接的最大数量。 当超过此数量时,最近使用的最少连接将关闭。
    应该特别注意的是,keepalive伪指令不限制nginx工作进程可以打开的到上游服务器的连接的总数。 连接参数应设置为足够小,以允许上游服务器处理新的传入连接。

    详细参考

  • 相关阅读:
    #sort 快速排序 20. 9.14
    #Trie Trie树调试模板 20.09.21
    #operator ——“Kruskal算法求最小生成树 中的 operator” ~20.8.17
    #STL #List 容器函数以及一些内置函数的用法
    刷题周记(三)——#最小生成树:Kruskal#二分图:染色法、匈牙利算法#拓扑#DFS:排列数字、n-皇后#BFS:走迷宫、八格码#List容器
    #周测 9 —— 高低位交换、Subsequences Summing to Sevens S、积木大赛、跳石头
    刷题周记(二)——KMP,Trie,最大异或对,(并查集)合并集合、连通块中点的数量、食物链,堆排序,单多源最短路、Dijkstra、bellman-ford、SPFA、Floyd、(堆优化)Prim
    4.SQL(数据库变更)
    3.SQL(查询)
    2.Oracle基本使用
  • 原文地址:https://www.cnblogs.com/cuchadanfan/p/6418002.html
Copyright © 2011-2022 走看看