跳转到主要内容

这是本节的多页打印视图。 .

返回本页常规视图.

Nginx / Tengine

Nginx 模块、location、rewrite、Tengine

共 6 篇文档。

1 - Nginx 常用命令

启动命令

  1. linux 启动方式
# -c 指定 nginx 配置文件
nginx -c /path/conf/nginx.conf

# -p 指定 nginx 所在路径前缀,启动时会根据前缀路径查找 conf 文件夹下的 nginx.conf 配置文件
nginx -p /path/
  1. window 启动方式

# 注意需要 nginx 的安装目录去执行命令,如果配置了 nginx 的环境变量,默认读取的用户用户的下的配置,需要 conf、logs 等相关文件夹复制到用户目录才行
start nginx

# 修改配置文件重新加载
nginx -s reload

其他常用命令


# 查看帮助信息
nginx [-h | -?]
  1. -?,-h : 查看帮助信息
  2. -v : 显示版本信息
  3. -V : 显示版本信息和编译配置参数
  4. -t : 测试配置文件是否正确
  5. -T : 测试配置文件是否正确,同时输出所有有效配置内容
  6. -q : 在配置测试期间禁止显示非错误消息
  7. -s signal : 向主进程发送信号,常用的信号有 stop 快速关闭, quit 正常关闭, reopen 重新打开日志文件, reload 重新加载配置文件,启动一个加载新配置文件的 Worker Process, 正常关闭一个加载旧配置文件的 Worker Process
  8. -e filename : 指定 error 文件路径
  9. -c filename : 指定配置文件路径
  10. -g directives : 指定全局配置指令, 如:nginx -g “daemon off;”

2 - Nginx 知识点

root 和 alias 的区别

Nginx 中 root 是路径拼接,alias 是路径替换,二者决定请求 URI 如何映射到磁盘文件路径。

维度rootalias
路径逻辑根路径 + 完整请求 URI(追加)别名路径 + 去掉 location 匹配前缀后的剩余 URI(替换)
适用上下文http、server、location仅 location
末尾斜杠可有可无(不影响拼接)建议以 / 结尾(否则可能被当作文件导致错误)
正则匹配无需捕获组必须包含捕获组且 alias 引用(官方要求)
典型场景URI 与目录结构一致需将 URI 映射到不同目录

简单示例

  1. root 示例
location /img/ {
    # 映射真实路径为:root 路径 + 完整请求 URL
    root /data/dist;
}

请求 /img/top.gif → 映射到 /data/dist/img/top.gif。

  1. alias 示例
location /img/ {
    # 映射真实路径为:alias 路径 + 去掉匹配前缀的 URL
    alias /data/dist/images;
}

请求 /img/top.gif → 映射到 /data/dist/images/top.gif。

  1. location 正则匹配时,alias 必须引用正则捕获组,root 无此限制
# alias 正则示例
location ~ ^/img/(.+\.(gif|jpe?g|png))$ {
    # location 使用正则匹配,alias 必须使用正则捕获组
    alias /data/dist/images/$1;
}

请求 /img/top.gif → 映射到 /data/dist/images/top.gif。

3 - tengine 安装笔记

编译安装 nginx 淘宝定制的

  1. 官网下载 tengine
  2. 解压文件 tar zxvf tengine-2.3.3.tar.gz
  3. cd tengine-2.3.3
  4. ./configure
  5. make
  6. sudo make install 默认会将 tengine 安装到 /usr/local/nginx 下
  7. 编译提示 error: the HTTP rewrite module requires the PCRE library 安装 yum -y install pcre-devel
  8. 编译提示error: SSL modules require the OpenSSL library安装 yum -y install openssl openssl-devel

注意使用 ./configure 生成 makefile 时,可以使用 ./configure --help 查看其有哪些参数可设置,其中部分参数例子,使用如下:

# --prefix 参数指定安装目录,--add-module 指定要安装的第三方模块目录,使用 --without 禁用默认模块,使用 --with 启动默认的模块
./configure --prefix=/usr/local/nginx --add-module=/home/sysadmin/ngx_log_if-master --add-module=xxxxx --without-stream_return_module

将 nginx 注册为系统服务在 /lib/systemd/system/ 目录创建 nginx.service 文件,如下:

[Unit]
Description=nginx service
After=network.target
[Service]
Type=forking
# 指定启动命令
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target

nginx 服务启动的相关命令:

systemctl start nginx.service 启动nginx服务
systemctl stop nginx.service 停止服务
systemctl restart nginx.service  重新启动服务
systemctl list-units --type=service   查看所有已启动的服务
systemctl status nginx.service  查看服务当前状态
systemctl enable nginx.service  设置开机自启动
systemctl disable nginx.service 停止开机自启动

nginx1.18 以后动态添加模块

运行命令 nginx -V 查看 nginx 已经安装了哪些模块,运行命令后显示示例结果如下:

Tengine version: Tengine/2.3.2
nginx version: nginx/1.17.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx  --add-module=/home/sysadmin/ngx_log_if-master

重新使用 ./configure 生成新的 makefile 时,需要把旧 nginx 程序中的 configure arguments中的参数也要带上,不然已安装或者禁止的模块会丢弃。

./configure --prefix=/usr/local/nginx --add-module=/home/sysadmin/ngx_log_if-master --add-module=新增第三方的模块

./configure 之后,然后运行 make 编译生成新的 nginx 程序,注意make 之后,不要make install因为 make install 是覆盖安装。 make 完之后新的 nginx 程序会生成在跟 configure 同级的 objs 目录中。运行 ./objs/nginx -V 如果看到编译参数已经变成新编辑的参数,说明编译成功。

将新编译生成的 nginx 覆盖原来的 nginx 即可,注意备份原来的 nginx

4 - location 和 rewrite 笔记

location 指令

location 指令由 ngx_http_core_module 模块提供,官方文档说明

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

The matching is performed against a normalized URI, after decoding the text encoded in the “%XX” form, resolving references to relative path components “.” and “..”, and possible compression of two or more adjacent slashes into a single slash.

匹配是针对标准化的 URI 执行的,故在执行前,会将 URI 中以 %XX 形式编码的文本先进行解码、及解析对相对路径中 . 和 .. 组件的引用,和尽可能的去将路径中 // 压缩替换成 /。

A location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding “*” modifier (for case-insensitive matching), or the “” modifier (for case-sensitive matching). To find location matching a given request, nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered. Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used. If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.

location 的 URI 匹配规则可以使用前缀字符串定义,也可以由正则表达式定义。使用正则表达式,前缀指定 ~* 修饰符(用于不区分大小写的匹配)或 ~ 修饰符(适用于区分大小写匹配)。查找 location 匹配请求时,nginx 会优先检查匹配使用前缀字符串定义的 location,如果存在多个匹配的前缀字符串 location,则会取优先选择最长前缀字符串的 location 记录起来,然后按照正则表达式在配置文件中的出现顺序检查匹配正则表达式 location,搜索匹配到第一个正则表达式 location 时,就会终止查找匹配,并使用该正则表达作为最终的匹配结果。如果找不到匹配的正则表达式 location,则使用前面记录的的前缀字符串 location。

location blocks can be nested, with some exceptions mentioned below.

location 语句块是可以嵌套的,除了下面提到的一些情况是例外的。

For case-insensitive operating systems such as macOS and Cygwin, matching with prefix strings ignores a case (0.7.7). However, comparison is limited to one-byte locales.

对于 macOS 和 Cygwin 等不区分大小写的操作系统,匹配前缀字符串 location 会忽略大小写( 0.7.7 版本)。然而,比较仅限于一个字节的区域设置。

Regular expressions can contain captures (0.7.40) that can later be used in other directives.

正则表达式可以包含捕获(0.7.40),稍后可以在其他指令中使用。

If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.

如果匹配最长的前缀字符串 location 前缀使用 ^~ 修饰符,则不会在继续检查匹配正则表达式 location。

Also, using the “=” modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates. For example, if a “/” request happens frequently, defining “location = /” will speed up the processing of these requests, as search terminates right after the first comparison. Such a location cannot obviously contain nested locations.

当然,使用 = 修饰符定义的前缀字符串 location,它会精准匹配 URI。如果精准匹配 location 匹配上了,就会终止后续的匹配。例如,如果一个 / 频繁的请求,使用 = 符号,定义一个 location = / 精准匹配,将加快对这些请求的处理,由于匹配上第一精准的 location 之后就在终止继续查找匹配。像这样的 location 显然是不能嵌套另一个 location 的。

In versions from 0.7.1 to 0.8.41, if a request matched the prefix location without the “=” and “^~” modifiers, the search also terminated and regular expressions were not checked.

在 0.7.1 到 0.8.41 版本中,如果请求与前缀字符串的 location 匹配,但没有 = 和 ^~ 修饰符,也会终止检查匹配,并且不检查正则表达式。

Let’s illustrate the above by an example:

让我们通过一个例子来说明以上内容:

# 精准匹配,完整的匹配请求的 URI
location = / {
    [ configuration A ]
}

# 普通前缀匹配
location / {
    [ configuration B ]
}

# 普通前缀匹配
location /documents/ {
    [ configuration C ]
}

# 普通字符串前缀匹配 + 优先级提升,前缀匹配到后,就不再匹配正则表达式
location ^~ /images/ {
    [ configuration D ]
}

# 不区分大小写正则表达式匹配
location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}

# 区分大小写正则表达式匹配
location ~ \.(css|js)$ {
    [ configuration F ]
}

The “/” request will match configuration A, the “/index.html” request will match configuration B, the “/documents/document.html” request will match configuration C, the “/images/1.gif” request will match configuration D, and the “/documents/1.jpg” request will match configuration E.

访问 / 请求会匹配 configuration A,访问 /index.html 请求会匹配 configuration B,访问 /documents/document.htm 会匹配 configuration C,访问 /images/1.gif 请求会匹配 configuration D,和访问 /documents/1.jpg 请求会匹配 configuration E。

The “@” prefix defines a named location. Such a location is not used for a regular request processing, but instead used for request redirection. They cannot be nested, and cannot contain nested locations.

@ 符号前缀定义命名 location,这样定义的 location 不能用于常规请求处理,但是可以嵌套在其他 location 中用于请求重定向和转发请求,它们自身是不能嵌套其他 locations 的。

If a location is defined by a prefix string that ends with the slash character, and requests are processed by one of proxy_pass, fastcgi_pass, uwsgi_pass, scgi_pass, memcached_pass, or grpc_pass, then the special processing is performed. In response to a request with URI equal to this string, but without the trailing slash, a permanent redirect with the code 301 will be returned to the requested URI with the slash appended. If this is not desired, an exact match of the URI and location could be defined like this:

如果一个 location 的匹配规则使用前缀字符定义,并且结尾是 / 字符,并且请求由 proxy_pass、fastcgi_pass、uwsgi_pass、scgi_pass、memcached_pass 或 grpc_pass 其中的一个处理,则会执行响应特殊处理。

一个请求 URI 与响应(转发)的 URI 前缀路径相同,但是响应(转发)的 URI,不是以 / 结尾的,将会返回代码为 301 的永久重定向到 以 ‘/’ 结尾的请求 URI。如果不希望这样做,可以定精确匹配 location 来匹配 URI,如下面的例子:

location /user/ {
    proxy_pass http://user.example.com;
}

location = /user {
    proxy_pass http://login.example.com;
}

参考链接

  1. location 官方文档
  2. 在线测试 nginx 链接

5 - ngx_http_proxy_module 模块学习笔记

介绍

The ngx_http_proxy_module module allows passing requests to another server.

ngx_http_proxy_module 模块允许转发请求到其他的服务器,即我们平时所说的反向代理。

proxy_pass 指令

官网语法说明

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

该指令用于设置请求匹配 location 后,转发的代理服务器的 protocol 和 address 以及可选 URI。protocol 可以指定使用 http 或者 https,adress 可以指定为域名或者 ip 地址和可选的端口号(没有端口则默认端口 80),使用例子如下:

# protocol:address:port
location / {
    proxy_pass http://127.0.0.1;
}

# protocol:address:port/uri
location / {
    proxy_pass http://127.0.0.1:90/test;
}

#  UNIX-domain socket
location / {
    proxy_pass http://unix:/tmp/backend.socket:/uri/;
}

请求的转发规则如下:

  • 如果 proxy_pass 指令带有 URI,那么当请求需要转发到服务器时,请求 URI 与 location 匹配的前缀部分字符串,将会被替换成 proxy_pass 指令中指定的 URI。 故请求的最终转发地址等于:proxy_pass-host + request-uri.replace前缀(location-prefix-uri, proxy_pass-uri)

    # 转发的替换公式:http://127.0.0.1:8080 + request-uri.replace前缀(location-prefix-uri, proxy_pass-uri),注意 request-uri 是包含请求参数的。
    # 访问 http://127.0.0.1/name/ 时,nginx 会将请求 URI = /name/ 与 location 前缀匹配字符串 /name/ 匹配的替换成 proxy_pass 的 URI = /remote/ 则转发后的地址为 http://127.0.0.1:8080/remote/
    # 访问 http://127.0.0.1/name/user?name=90 时,nginx 会将请求 URI 与 location 匹配的 /name/ 部分替换成 /remote/,则转发后的地址为 http://127.0.0.1:8080/remote/user?name=90
    location /name/ {
        proxy_pass http://127.0.0.1:8080/remote/;
    }
    
    # 访问 http://127.0.0.1/test 时,nginx 会将请求 URI 与 location 匹配的 /test 部分替换成 proxy_pass 的 URI(/remote), 则替换后的转发 URI = /remote
    # 访问 http://127.0.0.1/test/hello 时,nginx 会将请求 URI 与 location 匹配的 /test 部分替换成 proxy_pass 的 URI(/remote),则替换后的转发 URI = /remote/hello
    location /test {
        proxy_pass http://127.0.0.1:8080/remote;
    }
    
    # 访问 http://127.0.0.1/hello 时,前缀不匹配该 location
    # 访问 http://127.0.0.1/hello/ 时,nginx 会将请求 URI(/hello/) 与 location 匹配的 /hello/ 部分替换成 proxy_pass 的 URI(/remote), 则替换后的转发 URI = /remote
    # 访问 http://127.0.0.1/hello/world 时,nginx 会将请求 URI(/hello/) 与 location 匹配的 /hello/ 部分替换成 proxy_pass 的 URI(/remote),则替换后的转发 URI = /remotehello
    location /hello/ {
        proxy_pass http://127.0.0.1:8080/remote;
    }
    
    # 以下,是另一种表达方式
    
    # 访问 http://127.0.0.1/test/adc?param=xxx , location 匹配到请求的 URI = /test/adc 后,nginx 会将请求 URI 中与 location 匹配的前缀字符 / 去掉,变成 test/adc 后,
    # 再匹配拼接到 proxy_pass 的 URI 中,则转发后的地址是 http://127.0.0.1/pathtest/adc?param=xxx
    location / {
        proxy_pass http://127.0.0.1/path;
    }
    
    # 访问 http://127.0.0.1/get/test 时,location 匹配到请求的 URI = /get/test 后,会将请求 URI 中与 location 匹配的 /get 前缀字符串去掉,然后将剩余部分 /test,再拼接到 proxy_pass URI 中,则最终的转发地址为 http://127.0.0.1/get/path/test
    location /get {
    proxy_pass http://127.0.0.1/get/path;
    }
  • 如果 proxy_pass 指令没有带有 URI,那么当请求转发到服务器时,转发后的 URI,就是请求匹配 location 的 URI。

location /some/path/ {
    proxy_pass http://127.0.0.1;
}

# 等价于

location /some/path/ {
    proxy_pass http://127.0.0.1:8080$request_uri;
}

访问 http://127.0.0.1/some/path 则转发后的地址为 http://127.0.0.1:8080/some/path

访问 http://127.0.0.1/some/path/test 则转发后的地址为 http://127.0.0.1:8080/some/path/test

访问 http://127.0.0.1/some/path?param=xxx 则转发后的地址为 http://127.0.0.1:8080/some/path?param=xxx

注意以下几种情况是 proxy_pass 指令不能携带 URI 的

  • 如果 location 的匹配规则使用的是正则表达,proxy_pass 不能携带 URI
# 区分大小写正则表达式匹配 URI
location ~ /path {
    # 不能携带 URI,否则会报错
    proxy_pass http://127.0.0.1;
}

# 不区分大小写正则表达式匹配 URI
location ~* /case-insensitive /path/ {
   # 不能携带 URI,否则会报错
   proxy_pass http://127.0.0.1;
}
  • 当在 location 中使用 rewrite 指令时,proxy_pass 指令不能携带 URI
location /name/ {
    rewrite    /name/([^/]+) /users?name=$1 break;
    # rewrite 匹配不成功时,执行 proxy_pass
    proxy_pass http://127.0.0.1;
}
  • 在具名的 location 中 proxy_pass 指令不能携带 URI
location @testname {
    # 注意不能指定 URI
    proxy_pass http://127.0.0.1;
}
  • 在 if 条件中 proxy_pass 指令不能携带 URI

location /test {
    if ($host = "test.adb.com" ){
        # 不能携带 URI
        proxy_pass http://127.0.0.1;
    }
    if ($host = "view.adb.com" ) {
        # 不能携带 URI
        proxy_pass http://127.0.0.1;
    }
    # 这里可以
    proxy_pass http://127.0.0.1/user;
}

参考链接

  1. 在线测试 nginx 链接

6 - ngx_http_rewrite_module 模块学习笔记

介绍

ngx_http_rewrite_module 主要用于改变请求的 URI,通过 PCRE 正则表达式,return 指令,以及有选择的配置条件去改变。

模块中的 break、if、return、rewrite 和 set 指令会按以下顺序执行处理:

  • 在同一级别指令语句块中按配置文件中出现的位置,按顺序执行;
  • 如果对一个请求 URI 使用 rewrite 重定向,限制最多只能重定向 10 次。

一个 URL 请求到达 nginx 时,nginx 先会顺序执行 server 指令语句块中的 ngx_http_rewrite_module 指令集合,如果执行到 break 指令会直接返回 404,执行到 return 指令也会直接返回,执行到 rewrite 如果匹配 rewrite 表达式,将会重写请求的 URI 然后使用重写后的 URI 再去匹配 location。如果 server 指令语句块中没有 ngx_http_rewrite_module 指令集合或者有匹配不到的情况下,请求的 URL 则会去匹配 location。

ngx_http_rewrite_module 模块指令日志记录,记录在 error_log 文件中的,且日志的级别需要改成 notice 级别。rewrite 指令的日志还需要开启 rewrite_log。

rewrite_log on;
error_log  logs/error.log notice;

break 指令

break 指令的官网语法如下:

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

break 用于终止 ngx_http_rewrite_module 指令集合,即同一个指令块作用域内的指令集合。使用例子说明如下:

http {

    # ngx_http_rewrite_module 模块中的指令的优先级比 ngx_http_core_module 模块中的指令高。
    server {


        # 访问 127.0.0.1/b3 时,依次顺序执行 ngx_http_rewrite_module 指令,执行 break 执行后,将无法在执行后面的  rewrite ^/b3 /test/b3 指令,故会返回 404。
        rewrite ^/b1 /test/b1;
        rewrite ^/(b2) /test/$1;
        # 执行到 break 指令, 将不会执行下面的 rewrite,因为 break 指令会终止 ngx_http_rewrite_module 模块中的指令执行
        break;
        rewrite ^/b3 /test/b3;


        location /test/b3 {
            add_header Content-Type 'text/html; charset=utf-8';
            return 200 "Hello My is test-b3";
        }

        location /test {
            # 注意 break 只能终止 ngx_http_rewrite_module 指令集合,所以执行 break 指令后, return 不会在执行,但是会执行 pass_proxy
            break;
            return 200 "this test break ";
            pass_proxy: 127.0.0.1/xxx/
        }

        location /break {
            # 通过 break 语句,控制改走 return 还是走 pass_proxy
            if ( $uri == '/break/xx') {
                break;
            }
            # 上面的 if 指令满足后,执行 break 指令,会终止 return 执行,然后运行 pass_proxy 执行,如果条件不满足,不执行 break 则会执行 return 语句直接返回,就会执行不到 pass_proxy 指令
            return 200 "this test break ";
            pass_proxy: 127.0.0.1/break
        }
    }
}

if 指令

if 指令的官方语法如下:

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

if 指令支持的判断条件如下:

  1. 空字符串和 0 默认 false,在 1.0.1 版本之前,任何以 0 开头的字符串也被认为是 false
set $var 0;
location /test {
     add_header Content-Type 'text/html; charset=utf-8';
    if ($var) {
       return 200 "this is true";
    }
    return 200 "this is flase";
}
  1. 变量和字符串比较只支持 = 和 != 符号
location /test {
    add_header Content-Type 'text/html; charset=utf-8';
    if ($request_method = POST) {
        return 200 "this is POST method";
    }
    # 变量支持在字符串中使用
    return 200 "unkown $request_method method";
}
  1. 支持变量和正则表达式匹配,~ 符号表示区分大小写匹配,~* 表示不区分大小写匹配,正则匹配支持非运算符 !~ 和 !~*,同时支持捕获组,捕获组可通过 $1..$9 变量获取值。 如果正则表示式包含 } 和 ; 符号,那么正则表达式必须使用引号包起来。
location /test {
     add_header Content-Type 'text/html; charset=utf-8';
    if ($http_cookie ~* "id=([^;]+)(?:;|$)") {
       return 200 "id = $0";
    }
    return 200 "hello world";
}
  1. 支持使用 -f 和 !-f 符号检查文件是否存在
location /exists {
    add_header Content-Type 'text/html; charset=utf-8';
    if (-f C:/DevTools/nginx-1.22.1/html/index.html) {
        return 200 "file is exists";
    }
    return 200 "file is not exists";
}
  1. 支持使用 -d 和 !-d 符号检查目录是否存在
location /exists {
    add_header Content-Type 'text/html; charset=utf-8';
    if (-d C:/DevTools/nginx-1.22.1/html) {
        return 200 "dir is exists";
    }
    return 200 "dir is not exists";
}
  1. 支持使用 -e 和 !-e 运算符检查文件、目录或符号链接是否存在
location /exists {
    add_header Content-Type 'text/html; charset=utf-8';
    if (-e C:/DevTools/nginx-1.22.1/html/index.html) {
        return 200 "dir is exists";
    }
    return 200 "dir is not exists";
}
  1. 支持使用 -x 和 -x 运算符检查可执行文件
location /exec {
    add_header Content-Type 'text/html; charset=utf-8';
    if (-x C:/DevTools/nginx-1.22.1/nginx.exe) {
        return 200 "file is exec";
    }
    return 200 "file is not exec";
}
  1. 不支持与或逻辑符号判断,但是可以通过变量拼接字符串的形式实现
set $flag  "";
location /test {
    if ($request_method = POST) {
        set $flag "$flag1";
    }
    if ($protocol = HTTP) {
        set $flag "$flag1";
    }
    if ($flag = "11") {
        return 200 "this is and ";
    }
    return 200 "hello world"
}

rewrite 指令

rewrite 指令的官方语法如下:

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

If the specified regular expression matches a request URI, URI is changed as specified in the replacement string. The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with “http://”, “https://”, or “$scheme”, the processing stops and the redirect is returned to a client.

如果指定的 regex 正则表达式匹配请求的 URI, URI 将会被替换成指定 replacement 字符串。重写指令按照它们在配置文件中出现的顺序依次执行。可以使用标志符来终止对指令的进一步处理。如果 repalcement 字符串以 “http://"、“https://” 或 “$scheme” 开头,则停止处理并将重定向返回给客户。

falg 可选值说明:

  • last:表示 regex 正则表达式匹配到 URI 后立即停止处理当前 ngx_http_rewrite_module 指令集合,并用 replactment 后的 URI 匹配查找 location
  • break:表示 regex 正则表达式匹配到 URI 停止处理当前 ngx_http_rewrite_module 指令集合,如同处理 break 指令一样
  • redirect:返回一个状态是 302 的临时重定向
  • permanent:返回一个状态是 301 的永久重定向

永久重定向和临时重定向的区别是:浏览器会缓存永久重定向会记录,比如浏览器第一次访问 A 链接,如果返回 301 永久重定向到 B 链接,浏览器就会缓存 A 链接到 B 链接重定向记录,当浏览器再访问 A 链接时,如果缓存中有重定向记录则会直接重定向到 B 链接。如果第一次访问返回的 302 临时重定到 B 链接,浏览器每次都会重新 A 链接由 nginx 判断是不是重定向。即永久重定向会读缓存减轻服务器压力,临时重定向不会缓存,因为是临时的,临时说明随时会改变的所以不能缓存起来。

rewrite 指令在 server 指令语句块的例子说明:


http{

    # 注意,在同一指令语句块中所有的 rewrite 指令是一个集合,nginx 会按顺序匹配,并且优选高于 location,在 server 指令中使用 last 和 break 符号,其效果是一样的。
    server{

        # 没有使用 last 或者 break 标识符,如访问 127.0.0.1/test  会按 rewrite 指令的顺序去匹配 /test ,匹配到 ^/test 后,还会继续使用重写后的 URI 重写匹配,一直往下匹配到 test5,然后在使用 test5 去匹配查找 location
        rewrite ^/test /test1;
        rewrite ^/test1 /test2;
        rewrite ^/test2 /test3;
        rewrite ^/test3 /test4;
        rewrite ^/test4 /test5;


        # 如访问 127.0.0.1/last2 时,nginx 会按顺序从上面的 ^/test 开头的 rewirte 一直到 ^/last2 时匹配成功,重写 URI 为 /last3 因为 last 标识符结尾,所以直接终止匹配,然后使用 /last3 去匹配 location,
        # 如果能匹配查找到 location 则返回结果,否则直接返回 404
        rewrite ^/last /last1 last;
        rewrite ^/last1 /last2 last;
        rewrite ^/last2 / last3 last;


        # 注意, 如果重写的 URI 使用的是 http 协议开头,则相当于临时重定向,会直接返回给浏览器,浏览器在重定向请求新的 URL。只有重写请求的 URI 部分,nginx 才会去重新执行后续的 rewrite 或者匹配查找 location
        rewrite ^/redirect http://127.0.0.1/test.com;
        rewrite ^/redirect/last http://127.0.0.1/test.com last;
        rewrite ^/redirect/break http://127.0.0.1/test.com break;


        # 如访问访问 127.0.0.1/hello 也是先匹配 rewrite 集合如果匹配不到,再匹配查找 location,如果都匹配不到的话,nginx 会直接返回 404
        location /hello {

        }

        location /last3 {
            add_header Content-Type 'text/html; charset=utf-8';
            return 200 "this is /last2 rewrite /last3"
        }

        location /test5 {
            add_header Content-Type 'text/html; charset=utf-8';
            return 200 "this is /test rewrite /test5"
        }

    }

}

在 location 指令中的 rewrite 指令例子:

location /break {
    # location 中的 rewrite 使用 break 标识,如果匹配了,就会去访问 nginx 安装目录下 html 目录的 test/page 文件
    rewrite ^/break /test/page break;
    # 如果 rewrite 不匹配,执行 return
    add_header Content-Type 'text/html; charset=utf-8';
    return 200 "can't match rewrite, so return";
}

location /last {
    # location 中的 rewrite 如果使用 last 标识,根 server 指令中的效果一致
    rewrite ^/break /test last;
    # 匹配不通过就走 return, 因为 return 的优先级比 pass_proxy 高
    pass_proxy 127.0.0.1/hello;
    return 200 "Hello this is last";
}

获取正则表达的值:

# 访问 http://127.0.0.1/download/public/media/test.mp3
location /download/ {
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  break;
    return  403;
}

return 指令

return 的官方语法如下:

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

常用例子如下:


# 单独返回状态码
location /return0 {
    return 404;
}

# 返回字符串
location /return1 {
    add_header Content-Type 'text/html; charset=utf-8';
    return 200 "request is success";
}

# 302 重定向请求
location /return2 {
    return https://baidu.com;
    # 或者
    return 302 https://baidu.com;
}

# 返回内置变量
location /return3 {
    return 200 "请求的 URI : $uri ,请求的IP地址:$remote_addr";
}

set 指令

set 指令用于定义变量,其官方语法如下:

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

常用例子如下:

http {

    set hostname xx.test.com;

    server {

        location / {

        }
    }

}

参考链接

  1. https://nginx.org/en/docs/http/ngx_http_rewrite_module.html