Nginx指令

扫码查看

Nginx配置指令

参考: https://nginx.org/en/docs/
-

事前注意:配置Nginx和配置Apache不一定,Nginx必须要在指定的部分添加指令,否则会报错。

(1)user

指定worker进程的运行身份,如果组不指定,默认和用户名同名。

Syntax:    user user [group];
Default:
user nobody nobody;  这里需要注意下如果系统中默认有nginx账户,不会使用nobody账户运行。
Context:    main   规定只能在main定义此指令

(2)pid /PATH/TO/PID_FILE

指定存储nginx主进程PID的文件路径

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

(3)include file |mask

指明包含进来的其他配置文件片段

Syntax:    include file | mask;
Default:    —
Context:    any

(4)load_module file

指明加载模块的路径

模块加载配置文件:/usr/share/nginx/modules/*.conf

指明要装载的动态模块路径:/usr/lib64/nginx/modules

Syntax:    load_module file;
Default:    —
Context:    main
This directive appeared in version 1.9.11. 此指令在1.9.11版本中才有

性能优化相关指令

(1)worker_process number|auto

worker进程的数量,通常应该设置为小于或等于当前主机CPU的物理核心数

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

(2)worker_cpu_affinity auto [cpumask]

指定运行在哪些CPU上

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

示例:

worker_processes    4;
worker_cpu_affinity 0001 0010 0100 1000;

查看工作在哪颗CPU的命令

ps axo pid,cmd,psr,ni |grep nginx

(3)worker_priority number

指定worker进程nice值,设置worker进程优先级[-20,20],不过正常的话nice值为[-20,19]

Syntax:    worker_priority number;
Default:    worker_priority 0;
Context:    main

(4)worker_rlimit_nofile number

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

Syntax:    worker_rlimit_nofile number;
Default:    —
Context:    main

事件驱动相关指令:

(1)worker_connections number

每个worker进程所能够打开的最大并发连接数量

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

(2)use method

指明并发连接请求的处理方法,默认自动选择最优方法,默认使用epoll

Syntax:    use method;
Default:    —
Context:    events

(3)accept_mutex on|off

互斥处理新的连接请求方法

on:指由各个worker轮流处理新的请求
off:指每个新请求的到达都会通知所有的worker进程,但只有一个进程可获得连接,造成“惊群”,影响性能,默认为on

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

调试和定位问题

(1)daemon on|off

是否以守护进程方式运行nginx,默认为守护进程方式

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

(2)master_process on|off

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

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

(3)error_log file [level]

错误日志文件及其级别;出于调试需要可设置为debug;如果要是用debug,需要在编译使用“–with-debug”选项

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

stderr:发送到标准错误
syslog:server-address[,parameter=values]:发送到syslog
memory: size内存
level:debug|info|notice|warn|error|crit|alter|emerg

(4)time_resolution

计时器解析度;降低此值,可减少gettimeofday()系统调用的次数

Syntax:    resolver_timeout time;
Default:
resolver_timeout 30s;
Context:    mail, server

http协议的相关指令

(1)server{…}

配置一个虚拟主机

(2)listen PORT|address[:port]|unix:/PATH/TO/SOCKET_FILE

listen address[:port] [default_server] [ssl] [http2 | spdy] [backlog=number] [rcvbuf=size] [sndbuf=size]

Default:  listen *:80 | *:8000;
Context:    server

default_server:设置为默认虚拟主机
ssl :限制仅能够通过ssl连接提供服务
backlog=number:超过并发连接数后,新请求进入后院队列的长度
rcvbuf=size:接受缓冲区大小sndbuf=size发送缓冲区大小

示例:

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

注意:

  • (1)基于port

    listen PORT;指令监听在不同的端口

  • (2)基于IP的虚拟主机

    listen IP:PORT;IP地址不同

  • (3)基于hostname

    server_name FQDN:指令指向不同的主机名

listen只能放在server端中

(3)server_name name …;

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

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

server_name支持“*”通配任意长度的任意字符

示例:

server_name *.test.com

server_name支持“~”起始的字符做正则表达式匹配;此方法会消耗性能

server_name ~^wwwd+.test.com$

d表示[0-9]

匹配优先级

  • (1)首先是字符串精确匹配,www.test.com
  • (2)左侧通配符 .test.com
  • (3)右侧通配符 www.test.
  • (4)正则表达式 ~^wwwd+.test.com$
  • (5)default_server

(4)tcp_nodelay on|off

在keepalived模式下的连接是否启用tcp_nodelay

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

off:延迟发送,合并多个请求后再发送
on:不延迟发送

(5)sendfile on|off

是否启用sendfile功能,在内核封装报文直接发送

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

(6)server_tokens on|off|build|string

是否在响应报文的server首部显示nginx版本

Syntax:    server_tokens on | off | build | string;
Default:    server_tokens on;
Context:    http, server, location

定义路径相关指令

(1)root

设置web资源的路径映射;用于指明请求的URL所对应的文档的目录路径

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

示例:

location /i/ {
                root /data/w3;
}

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

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

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


^~:对URI的最左边部分做匹配检查,不区分字符大小写
~:对URI做正则表达式做模式匹配,区分字符大小写
~*:对URI做正则表达式模式匹配,不区分字符大小写
不带符号:匹配起始于URI的所有URI

匹配优先级从左到右降低

=  ^~  ~   ~* 不带符号

示例:

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

location ^~ /images/ {
    [ configuration D ]
}

location ~* .(gif|jpg|jpeg)$ {
    [ configuration E ]
}

(2)alias path

路径别名,文档映射的另一种机制;仅能用于location上下文

Syntax:    alias path;
Default:    —
Context:    location

alias和root指令的区别

(a)root指令给定的路径对应于localtion中的URI左侧的

(b)alias指令给定的路径对应于localtion中的URI右侧

示例:

http://www.test.com/bbs/index.html

location /bbs/ {
                 alias /web/forum/;
}

  --> /web/forum/index.html

location /bbs/ {
                root /web/forum/;
}

   --> /web/forum/bbs/index.html

(3)index file

指定默认网页资源;ngx_http_index_module模块提供

Syntax:    index file ...;
Default:   index index.html;
Context:    http, server, location

(4)error_page code …[=[response]] URI

定义错误页,以指定的响应码状态进行响应

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

示例:

error_page 404 /404.html
error_page 404 =200 /404.html

(5)try_files files … URI

按顺序检查文件是否存在,返回对一个找到的文件或文件夹(结尾加斜线表示文件夹);如果所有的文件或文件夹都找不到,会进行一个内部重定向到最后一个参数,只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的指向;最后一个参数是回退URI且必须存在,否则会出现内部500错误

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

示例:

location /images/ {
             try_files $uri /images/default.gif;
}
location / {
            try_files $uri $uri/index.html $uri.html =404;
}

定义客户端请求的指令

(1)keepalive_timeout timeout [header_timeout]

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

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

(2)keepalive——request number

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

Syntax:    keepalive_requests number;
Default:    keepalive_requests 100;
Context:    http, server, location

(3)keepalive——disable none|browser

对哪种浏览器禁用长连接

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

(4)send_timeout time

向客户端发送响应报文的超时时长,此处是指两次写操作之间的间隔时长,而非整个过程的传输时长

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

(5)client_body_buffer_size size

用于接受每个客户端请求报文的body部分的缓冲区大小;默认为16k,超出此大小时,将其暂存到磁盘上由client_body_temp_path指令所定义的位置,仅能应用于上传

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

(6)client_body_temp_path path [level 1 [level2 [level3]]]

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

目录名为16进制的数字
client_body_temp_path /var/tmp/client_body 1 2 2
1 :1级目录占1位16进制即2^4=16个目录 0-f
2:2级目录占2位16进制,即2^8=256个目录 00-ff
2:3级目录占2位16进制,即2^8=256个目录 00-ff

对客户端进行限制的相关指令

(1)limit_rate rate

限制响应给客户端的传输速率,单位为bytes/second,默认为0表示无限制

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

(2)limit_except method …{…},

限制客户端使用除了制定的请求方法之外的其他方法

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

method: GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, or PATCH.

示例:

limit_expect GET {
    allow 192.168.4.0./24;
    deny all;
}

文件操作优化指令

(1)aio on|off|threads[=pool]

是否开启aio功能

Syntax:    aio on | off | threads[=pool];
Default:    aio off;
Context:    http, server, location
This directive appeared in version 0.8.11.0.8.11版本以后才可以支持

(2)directio size|off

是否同步写磁盘,而非写缓存,在linux 主机启用O_DIRECT标记,则文件大于等于给定大小时使用

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

示例:

directio 4m 当文件大于或者等于4m开始同步磁盘

(3)open_file_cache off

open_file_cache max=N[inactive=time]

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

nginx可以缓存以下三种信息:

a、文件元数据:文件FD、文件大小和最近一次的修改时间

b、打开的目录结构

c、没有找到的或者没有权限访问的文件的相关信息

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

inactive=time:缓存项的非活动时长,在此处指令的时长内未被命中的或者命中次数少于open_file_cache_min_uses指令指定的次数的缓存项;即非活动项将被删除

(4)open_file_cache_errors on|off

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

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

(5)open_file_cache_min_uses number

open_file_cache指令的inactive参数指定的时长内,至少被命中此处指令的次数方可被归类为活动项

Sy 大专栏  Nginx指令ntax:    open_file_cache_min_uses number;
Default:    open_file_cache_min_uses 1;
Context:    http, server, location

(6)open_file_cache_valid time

缓存项有效检查频率

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

ngx_http_access_module 实现基于IP访问控制功能

(1)allow address|CIDR|unix:|all

指定允许访问的IP

(2)deny address | CIDR | unix: | all;

指定不能访问的IP

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

注意:检查规则为自上而下检查,一旦匹配,将生效;建议条件严格的放置前面。

示例:

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

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

(1)auth_basic string|off

是否可以认证功能或string

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

(2)auth_basic_user_file filename

认证文件的位置

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

用户口令方式:

a、明文文本

格式:

name:password:comment

b、加密文本:需要htpasswd工具实现,由httpd_tools安装包提供

格式:

USERNAME
PASSWORD

ngx_http_stub_stastus_module 用于输出nginx基本状态信息

stub_status

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

示例:

location /status {
    stub_status;
    allow 192.168.4.0/24;
    deny all;
}

显示信息解释:

active connection :当前状态,活动状态的连接数
accepts:统计总值,已经接受的客户端请求的总数
handled:统计总值,已经处理完成的客户端请求的总数
requests:统计总值,客户端发来的总的请求数
reading:当前状态,正在读取客户端的请求报文的链接数
writing:当前状态,正在向客户端响应报文过程中的连接数
waiting:当前状态,正在等待客户端发出请求的空闲连接数

ngx_http_log_module指定日志格式记录请求

(1)log_format name string …

nginx核心模块及其他模块内嵌的变量

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

(2) access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]]

access_log off; 是否开启日志功能

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

buffer=size 定义缓存区大小
gzip 定义日志压缩级别
flush 定义刷新时间

示例:

log_format compression '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $bytes_sent '
                   '"$http_referer" "$http_user_agent" "$gzip_ratio"';

access_log /spool/logs/nginx-access.log compression buffer=32k;

注意:为了使用压缩工作,必须安装zlib 库

(3)open_log_file_cache max=N[inactive=time][valid=time]

open_log_file_cache off;是否开启日志缓存

max:缓存的最大文件描述符数量
min_uses:在inactive指定的时长内访问大于等于此值认为活动项
inactive:非活动时长
valid:验证缓存中各缓存是否为活动项的时间间隔


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

ngx_http_gzip_module使用gzip方法压缩响应数据,可以节约带宽

(1)gzip on|off

是否启用gizp压缩

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

(2)gzip_comp_level level

指定压缩比 范围1-9

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

(3)gzip_disable regex …

匹配到客户端浏览器不执行压缩

Syntax:    gzip_disable regex ...;
Default:    —
Context:    http, server, location

(4)gzip_min_length length

启用压缩功能的响应报文大小阈值

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

(5)gzip_http_version 1.0|1.1

设定启用压缩功能时,协议的最小版本

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

(6)gzip_buffers number size

支持实现压缩功能时缓冲区数量及每个缓存区的大小

Syntax:    gzip_buffers number size;
Default:    gzip_buffers 32 4k|16 8k;
Context:    http, server, location

(7)gzip_type mime_type

指明仅对哪些类型的资源执行压缩操作;默认为test/html,不用再次指定,否则会报错。

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

(8)gzip_vary on|off

如果启用压缩,是否在响应报文首部添加“vary:Accept_Encoding”

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

(9) gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any …

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

nginx对于代理服务器请求的响应报文,在何种情况下启用压缩功能

off对于被代理的请求不启用压缩
expired,no-cache,no-store,private对代理服务器请求的响应报文首部Cache-Control值任何一个,启用压缩功能

示例:

gzip            on;
gzip_min_length 1000;
gzip_proxied    expired no-cache no-store private auth;
gzip_types      text/plain application/xml;

ngx_http_ssl_module

(1)ssl on|off

是否启用https protocol,建议用listen指令代替

listen 443 ssl

Syntax:    ssl on | off;
Default:    ssl off;
Context:    http, server

(2)ssl_certificate file

当前虚拟机使用证书文件路径

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

(3)ssl_certificate_key file

当前虚拟机使用证书的私钥文件

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

(4)ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2] [TLSv1.3

支持ssl协议版本

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

(5)ssl_session_cache off|none|[builtin[:sieze]][shared:name:size]

是否开启ssl会话缓存

none:相当于干跑
builtin[:size]:使用openssl内建缓存,为每个worker进程私有;
[shared:name:size]:在各worker之间使用一个共享缓存

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

(6)ssl_session_timeout time

客户端连接可以服用ssl session cache中缓存的ssl参数有效市场

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

示例:

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

查看证书

openssl s_client -connect www.test.com/443

注意:可以为每个FQDN提供不同的证书,这是在apache中不能实现的

server {
    listen 443 ssl;
    server_name www.test.com;
     root /vhosts/ssl/htdocs;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ssl_session_cache  shared:sslcache:20m;
    ssl_session_timeout 10m;
}
server {
    listen 443 ssl;
    server_name www.test2.com;
     root /vhosts/ssl/htdocs;
    ssl_certificate /etc/nginx/ssl/nginx2.crt;
    ssl_certificate_key /etc/nginx/ssl/ngin2x.key;
    ssl_session_cache  shared:sslcache:20m;
    ssl_session_timeout 10m;
}
server {
    listen 443 ssl;
    server_name www.test2.com;
     root /vhosts/ssl/htdocs;
    ssl_certificate /etc/nginx/ssl/nginx3.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx3.key;
    ssl_session_cache  shared:sslcache:20m;
    ssl_session_timeout 10m;
}

ngx_http_rewrite_module

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

(1)rewrite regex replacement[flag]

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

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

[flag]所表示的标志位用于控制此循环机制

last:重写完成后停止对当前URI在当前location中后续的其他重写操作,而后对新的URI启动新一轮重写检查;提前重启新一轮循环
break:重写完成后停止对当前URI在当前location中后续的其他重写操作,而直接跳转至重写规则之后的其他配置;结束循环,建议在location中使用
redirect:临时重定向,重写完成之后以临时重定向后生成新的URI给客户端,由客户端重新发起新的;不能以http://huo https://开头,使用相对路径,状态码为302
permanent:重写完成之后以永久重定向方式直接返回重写后生成新的URI给客户端,由客户端重新发起新请求:状态码为301

上述中last和break是在服务器内部做跳转;redirect和permanent是客户端做跳转

(2)return

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

停止处理,并返回客户端指定的响应码

(3)rewrite_log on|log

是否开启重写日志,发送至error_log

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

(4)set $variable value

用户自定义变量

注意:变量定义和调用都要以$开头

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

(5)if(condition){…}

引入新的上下文,条件满足时,执行配置块中的配置指令

==相同
!=不相同
~模式匹配,区分字符大小写
~*模式匹配,不区分大小写
!~ 和 !~*上述两种的否定

文件及目录存在性判断

-e,!-e存在,不存在
-f,!-f是否为文件
-d,!-d是否为目录
-x,!-x是否可执行

####注意:如果在同一级配置块中存在多个rewrite规则,那么会自上而下逐个检查,被某条件规则替换完成后,会重新一轮的替换检查。隐含有循环机制,但不超过10次,如果超过10此,提示500响应码

示例:

location /admin {
        return 403 “Not Found”;
}

location /admin {
        return 403 http://www.baidu.com;
}
location /admin {
        return http://www.baidu.com;
}

ngx_http_referer_module

(1)valid_referers none|blocked|server_names|string …

定义referer首部的合法可用值,不能匹配的将是非法值

Syntax:    valid_referers none | blocked | server_names | string ...;
Default:    —
Context:    server, location
none请求报文首部没有referer首部
blocked请求报文有referer首部,但无有效值,前段可能被代理服务器删除
server_names参数,其可以有值作为主机名或主机名模式
arbitrary_string任意字符串,但可使用*做通配符
regular experssion被指定的正则表达式模式匹配的字符串,要使用~开头

示例:

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

ngx_http_headers_module

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

(1)add_header name value [always]

添加自定义首部

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

(2)add_tralier name value [always]

添加自定义响应信息的尾部

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

示例:

add_header X-Via    $server_addr;
add_header X-Cache $upstream_cache_status;
 add_header X-Accel $server_name;
01-18 12:24
查看更多