# 命令

# 2.1 查看Nginx版本号
./nginx -v
#2.2 启动Nginx
./nginx

#2.7 测试配置文件是否正确
./nginx -t
1
2
3
4
5
6
7

nginx -s signal

其中signal可能是以下之一:

  • stop— 快速关机
  • quit— 优雅关机
  • reload— 重新加载配置文件
  • reopen重新生成日志文件当nginx正在运行期间,如果我们改了日志文件的名字或路径,日志照样会写到该文件

# 配置

# 配置文件所在位置
# /usr/local/nginx/conf/nginx.conf
# 由全局块+events块+http块组成
1
2
3

# 全局块

从配置文件开始到events之间的内容,主要会设置一些影响Nginx服务器整体运行的配置指令,主要包括配置运行Nginx服务器的用户(组)、允许生成的worker process数,进程pid存放路径、日志存放路径和类型以及配置文件的引入等。

worker_processes 1;
# worker_processes auto;
#这个是Nginx服务器并发处理服务的关键配置,worker_processes值越大,可以支持的并发处理量越多,但是会受到硬件、软件等设备的制约。
error_log log/error.log debug;  #制定日志路径,级别。这个设置可以放入全局块,http块,server块,级别以此为:debug|info|notice|warn|error|crit|alert|emerg

1
2
3
4
5

# events块

events块设计的指令主要影响Nginx服务器与用户的网络连接,常用的设置包括是否开启对多work process下的网络连接进行序列化,是否允许同时接收多个网络连接,选取哪种事件驱动模型来处理连接请求,每个work process可以同时支持的最大连接数等。下面的例子表示每个work process支持的最大连接数为1024。这部分配置对Nginx的性能影响较大,在实际中应该灵活配置。

events {
  use epoll;
  worker_connections 51200;
  multi_accept on;
}
1
2
3
4
5

# http块

Nginx服务器配置中最频繁的部分,代理、缓存和日志定义等绝大多数功能和第三方模块的配置都在这里,http块又包括http全局块和server块。

# http全局块

http全局块配置的指令包括文件引入、MIME-TYPE定义、日志自定义、连接超时时间、单链接请求数上限等。

http {
  include mime.types;
  default_type application/octet-stream;
  server_names_hash_bucket_size 128;
  client_header_buffer_size 32k;
  large_client_header_buffers 4 32k;
  client_max_body_size 1024m;
  client_body_buffer_size 10m;
  sendfile on;
  tcp_nopush on;
  keepalive_timeout 120;
  server_tokens off;
  tcp_nodelay on;

  fastcgi_connect_timeout 300;
  fastcgi_send_timeout 300;
  fastcgi_read_timeout 300;
  fastcgi_buffer_size 64k;
  fastcgi_buffers 4 64k;
  fastcgi_busy_buffers_size 128k;
  fastcgi_temp_file_write_size 128k;
  fastcgi_intercept_errors on;

  #Gzip Compression
  gzip on;
  gzip_buffers 16 8k;
  gzip_comp_level 6;
  gzip_http_version 1.1;
  gzip_min_length 256;
  gzip_proxied any;
  gzip_vary on;
  gzip_types
    text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
    text/javascript application/javascript application/x-javascript
    text/x-json application/json application/x-web-app-manifest+json
    text/css text/plain text/x-component
    font/opentype application/x-font-ttf application/vnd.ms-fontobject
    image/x-icon;
  gzip_disable "MSIE [1-6]\.(?!.*SV1)";

  ##Brotli Compression
  #brotli on;
  #brotli_comp_level 6;
  #brotli_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml;

  ##If you have a lot of static files to serve through Nginx then caching of the files' metadata (not the actual files' contents) can save some latency.
  #open_file_cache max=1000 inactive=20s;
  #open_file_cache_valid 30s;
  #open_file_cache_min_uses 2;
  #open_file_cache_errors on;

  log_format json escape=json '{"@timestamp":"$time_iso8601",'
                      '"server_addr":"$server_addr",'
                      '"remote_addr":"$remote_addr",'
                      '"scheme":"$scheme",'
                      '"request_method":"$request_method",'
                      '"request_uri": "$request_uri",'
                      '"request_length": "$request_length",'
                      '"uri": "$uri", '
                      '"request_time":$request_time,'
                      '"body_bytes_sent":$body_bytes_sent,'
                      '"bytes_sent":$bytes_sent,'
                      '"status":"$status",'
                      '"upstream_time":"$upstream_response_time",'
                      '"upstream_host":"$upstream_addr",'
                      '"upstream_status":"$upstream_status",'
                      '"host":"$host",'
                      '"http_referer":"$http_referer",'
                      '"http_user_agent":"$http_user_agent"'
                      '}';


# include放http最后
########################## vhost #############################
  include vhost/*.conf;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

# server块

这块和虚拟主机有密切关系,虚拟主机从用户角度看,和一台独立的硬件主机是完全一样的,该技术的产生是为了节省互联网服务器硬件成本。

每个http块可以包括多个server块,而每个server块就相当于一个虚拟主机。

每个server块也可以分为全局server块,以及可以同时包含多个location块。

# 反向代理
proxy_pass http://127.0.0.1:8080;


# 根据访问的路径跳转到不同的服务器中去
server {
    listen 9001;
    server_name 192.168.71.167;
    location ~/edu/ {
    proxy_pass http://127.0.0.1:8080;
    }
    location ~/vod/ {
    proxy_pass http://127.0.0.1:9090;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# location

一个server块可以配置多个location块。

这块的主要作用是基于Nginx服务器接收到的请求字符串(例如server_name/uri-string),对虚拟主机名称(也可以是IP别名)之外的字符串(例如前面的/uri-string)进行匹配,对特定的请求进行处理。地址定向、数据缓存和应答控制等功能,还有许多第三方模块的配置也在这里进行。

# location的匹配规则
  • ~ 波浪线表示执行一个正则匹配,区分大小写
  • ~* 表示执行一个正则匹配,不区分大小写
  • ^~ ^~表示普通字符匹配,如果该选项匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
  • = 进行普通字符精确匹配
  • @ #"@" 定义一个命名的 location,使用在内部定向时,例如 error_page, try_files 不用于常规请求处理
# 路径匹配
  • = 开头表示精确匹配。如 A 中只匹配根目录结尾的请求,后面不能带任何字符串;
  • ^~ 开头表示uri以某个常规字符串开头,不是正则匹配;
  • / 通用匹配, 如果没有其它匹配,任何请求都会匹配到。

一个location定义可以是一个前缀字符串,也可以是一个正则表达式。正则表达式使用的时候要在前面用“*”修饰符(用于不区分大小写匹配),或者“”修饰符(用于区分大小写)。为了找到请求匹配的location,nginx首先检查location定义,用前缀字符串(这些location成为前缀location)。其中,最长匹配前缀的location会被选中并记住。然后,检查正则表达式,按照它们在配置文件中出现的顺序。对正则表达式的搜索在第一次匹配时终止,并使用相应的配置。如果没有找到与正则表达式的匹配,则使用前面记住的前缀位置的配置。

1、用前缀字符串(前缀location)匹配URL,并且选中并记住最长匹配前缀的location(注意:是在匹配的里面记住最长的那个)

2、按照正则表达式在配置文件中出现的顺序依次去匹配,当匹配到第一个以后立即停止,并使用与之相应的那个location。如果没有一个正则表达式匹配,则使用之前记住的那个前缀location。

以上,我们可以得出一个结论:优先使用正则表达式,如果没有匹配的正则表达式发现,则使用匹配的最长前缀字符串location

location  = / {
  # 精确匹配 / ,主机名后面不能带任何字符串
  [ configuration A ]
}
location  / {
  # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求
  # 但是正则和最长字符串会优先匹配
  [ configuration B ]
}
location /documents/ {  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration C ]
}
location ~ /documents/Abc {  # 匹配任何以 /documents/Abc 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration CC ]
}location ^~ /images/ {  # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。
  [ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {  # 匹配所有以 gif,jpg或jpeg 结尾的请求
  # 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则
  [ configuration E ]
}
location /images/ {  # 字符匹配到 /images/,继续往下,会发现 ^~ 存在
  [ configuration F ]
}
location /images/abc {  # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在
  # F与G的放置顺序是没有关系的
  [ configuration G ]
}
location ~ /images/abc/ {  # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用
  # 因为都是正则匹配,优先级一样,选择最上面的
    [ configuration H ]
}
location ~* /js/.*/\.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# 优先级

( location = ) > ( location 完整路径 ) > ( location ^~ 路径 ) > ( location ,* 正则顺序 ) > ( location 部分起始路径 ) > ( / )

推荐使用

#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。#这里是直接转发给后端应用服务器了,也可以是一个静态首页
# 第一个必选规则
location = / {
    proxy_pass http://tomcat:8080/index
}
# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
#第三个规则就是通用规则,用来转发动态请求到后端应用服务器
#非静态文件请求就默认是动态请求,自己根据实际把握
#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了
location / {
    proxy_pass http://tomcat:8080/
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# root

location中root指定的只是相对路径,需要和路径结合起来映射地址,比如

location ^~/static/ {
## 这里的root需要和路径结合使用,即是映射的文件位置为 /usr/alyingboy/static
    root /usr/alyingboy/; 
    index index.html
}
1
2
3
4
5

此时我们访问 IP/static/a.css ,那么就会找到 /usr/alyingboy/static/a.css

# alias

alias指定的是绝对路径,不会和location中的路径结合使用,而是直接使用地址映射到文件,比如

location ^~/static/ {	## 不会路径结合映射地址,那么这里就会直接映射到/usr/alyingboy/文件夹下的文件
    alias /usr/alyingboy/; 
    index index.html
}
1
2
3
4

如果定义的路径是文件夹,那么需要使用/结尾


一旦配置请求location映射到了指定的位置,那么下面全部的文件夹和文件都可以映射到,不需要在配置对其的映射,比如 ,但是如果使用其中的文件名重新映射了地址,那么这个路径将不能使用

# /usr/alyingboy/文件夹下的全部文件包括子文件夹和文件都可以使用指定的地址访问到,
比如访问地址为 :# IP/static/a.txt,
那么这个地址访问的是/usr/alyingboy/static/a.txt文件
location / {
    root /usr/alyingboy/;
    index index.html;
}
1
2
3
4
5
6
7
# try_files
  • 语法:try_files file … uri;try_files file … = code;
  • 默认值:无
  • 作用域:server location

**注:**只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部的 URL 的指向。最后一个参数是回退 URL 且必须存在,否则会出现内部 500 错误。命名的 location 也可以使用在最后一个参数中。

例子:根据上面的配置,当请求 http://localhost:3004/api (opens new window) 时,$uri/api。当前try_file 具体为:/api/api//index.html,其中 / 表示根目录(根据 root 或 alias 来指定)。

查找逻辑:

  • 首先:检查 data 目录中是否存在 api 文件,如果存在,则返回文件;如果不存在,则进行下一步。
  • 其次:检查 data 目录中是否存在 api/ 目录,如果存在,则在检查 api/ 目录中是否存在 index.html 或者 index.htm 文件(由 index 指定);如果存在,则返回该文件。如果不存在,则进行下一步。
  • 最后:检查 data 目录中是否存在 index.html 文件。如果存在,则返回文件;如果不存在,则返回 404。
# index
  • index:设置目录的默认文件为 index.htmlindex.htm
# proxy_pass

在nginx中配置proxy_pass代理转发时,如果在proxy_pass后面的url加/,表示绝对根路径;如果没有/,表示相对路径,把匹配的路径部分也给代理走。

假设下面四种情况分别用 http://192.168.1.1/proxy/test.html 进行访问。

# 1:代理到URL:http://127.0.0.1/test.html
location /proxy/ {
    proxy_pass http://127.0.0.1/;
}
# 2(相对于第一种,最后少一个 / )代理到URL:http://127.0.0.1/proxy/test.html
    location /proxy/ {
    proxy_pass http://127.0.0.1;
    }
# 3:代理到URL:http://127.0.0.1/aaa/test.html
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa/;
}
# 4(相对于第三种,最后少一个 / )# 代理到URL:http://127.0.0.1/aaatest.html
location /proxy/ {
    proxy_pass http://127.0.0.1/aaa;
}   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

基本配置

location / {
		proxy_pass http://192.168.1.2:8080/;
	    proxy_redirect     off;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_max_temp_file_size 0;
        proxy_connect_timeout      90;
        proxy_send_timeout         90;
        proxy_read_timeout         90;
        proxy_buffer_size          4k;
        proxy_buffers              4 32k;
        proxy_busy_buffers_size    64k;
        proxy_temp_file_write_size 64k;
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# upstream

  • 1 轮询(默认)

每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

server {
    listen       80;
    #server_name localhost;
    server_name  192.168.71.167;
    location / {
        root   html;
					proxy_pass http://myserver;
					proxy_connect_timeout 10;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

upstream myserver{
  server 192.168.71.167:8080 weight=1;
  server 192.168.71.167:8081 weight=1;
  server localhost:8091;
  server localhost:8092;
  server localhost:8093;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  • 2 weight

weight代表权重,默认为1,权重越高被分配的客户端越多。

指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。

upstream myserver{
  server 192.168.71.167:8080 weight=1;
  server 192.168.71.167:8081 weight=1;
}
1
2
3
4
  • 3 ip_hash

每个请求按访问IP的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题,示例如下:

upstream myserver{
ip_hash;
server 192.168.71.167:8080 weight=1;
server 192.168.71.167:8081 weight=1;
}
1
2
3
4
5
  • 4 fair(第三方)

按后端服务器的响应时间来分配请求,响应时间短的优先分配。

upstream myserver{
fair;
server 192.168.71.167:8080 weight=1;
server 192.168.71.167:8081 weight=1;
}
1
2
3
4
5