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

Directives
     break
     if
     return
     rewrite
     rewrite_log
     set
     uninitialized_variable_warn
Internal Implementation

The ngx_http_rewrite_module module is used to change request URI using PCRE regular expressions, return redirects, and conditionally select configurations.

The breakifreturnrewrite, and set directives are processed in the following order:

  • the directives of this module specified on the server level are executed sequentially;
  • repeatedly:
    • location is searched based on a request URI;
    • the directives of this module specified inside the found location are executed sequentially;
    • the loop is repeated if a request URI was rewritten, but not more than 10 times.

Directives

Syntax: break;
Default:
Context: serverlocationif

Stops processing the current set of ngx_http_rewrite_module directives.

If a directive is specified inside the location, further processing of the request continues in this location.

Example:

if ($slow) {
limit_rate 10k;
break;
}
Syntax: if (condition) { ... }
Default:
Context: serverlocation

The specified condition is evaluated. If true, this module directives specified inside the braces are executed, and the request is assigned the configuration inside the if directive. Configurations inside the if directives are inherited from the previous configuration level.

A condition may be any of the following:

  • a variable name; false if the value of a variable is an empty string or “0”;

    Before version 1.0.1, any string starting with “0” was considered a false value.

  • comparison of a variable with a string using the “=” and “!=” operators;
  • matching of a variable against a regular expression using the “~” (for case-sensitive matching) and “~*” (for case-insensitive matching) operators. Regular expressions can contain captures that are made available for later reuse in the $1..$9 variables. Negative operators “!~” and “!~*” are also available. If a regular expression includes the “}” or “;” characters, the whole expressions should be enclosed in single or double quotes.
  • checking of a file existence with the “-f” and “!-f” operators;
  • checking of a directory existence with the “-d” and “!-d” operators;
  • checking of a file, directory, or symbolic link existence with the “-e” and “!-e” operators;
  • checking for an executable file with the “-x” and “!-x” operators.

Examples:

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;
}

A value of the $invalid_referer embedded variable is set by the valid_referers directive.

Syntax: return code [text];
return code URL;
return URL;
Default:
Context: serverlocationif

Stops processing and returns the specified code to a client. The non-standard code 444 closes a connection without sending a response header.

Starting from version 0.8.42, it is possible to specify either a redirect URL (for codes 301, 302, 303, 307, and 308) or the response body text (for other codes). A response body text and redirect URL can contain variables. As a special case, a redirect URL can be specified as a URI local to this server, in which case the full redirect URL is formed according to the request scheme ($scheme) and theserver_name_in_redirect and port_in_redirect directives.

In addition, a URL for temporary redirect with the code 302 can be specified as the sole parameter. Such a parameter should start with the “http://”, “https://”, or “$scheme” string. A URL can contain variables.

Only the following codes could be returned before version 0.7.51: 204, 400, 402 — 406, 408, 410, 411, 413, 416, and 500 — 504.

The code 307 was not treated as a redirect until versions 1.1.16 and 1.0.13.

The code 308 was not treated as a redirect until version 1.13.0.

See also the error_page directive.

Syntax: rewrite regex replacement [flag];
Default:
Context: serverlocationif

If the specified regular expression matches a request URI, URI is changed as specified in the replacementstring. 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.

An optional flag parameter can be one of:

last
stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
break
stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
redirect
returns a temporary redirect with the 302 code; used if a replacement string does not start with “http://”, “https://”, or “$scheme”;
permanent
returns a permanent redirect with the 301 code.

The full redirect URL is formed according to the request scheme ($scheme) and theserver_name_in_redirect and port_in_redirect directives.

Example:

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

But if these directives are put inside the “/download/” location, the last flag should be replaced bybreak, or otherwise nginx will make 10 cycles and return the 500 error:

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

If a replacement string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:

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

If a regular expression includes the “}” or “;” characters, the whole expressions should be enclosed in single or double quotes.

Syntax: rewrite_log on | off;
Default:
rewrite_log off;
Context: httpserverlocationif

Enables or disables logging of ngx_http_rewrite_module module directives processing results into the error_log at the notice level.

Syntax: set $variable value;
Default:
Context: serverlocationif

Sets a value for the specified variable. The value can contain text, variables, and their combination.

Syntax: uninitialized_variable_warn on | off;
Default:
uninitialized_variable_warn on;
Context: httpserverlocationif

Controls whether warnings about uninitialized variables are logged.

Internal Implementation

The ngx_http_rewrite_module module directives are compiled at the configuration stage into internal instructions that are interpreted during request processing. An interpreter is a simple virtual stack machine.

For example, the directives

location /download/ {
if ($forbidden) {
return 403;
} if ($slow) {
limit_rate 10k;
} rewrite ^/(download/.*)/media/(.*)\..*$ /$1/mp3/$2.mp3 break;
}

will be translated into these instructions:

variable $forbidden
check against zero
return 403
end of code
variable $slow
check against zero
match of regular expression
copy "/"
copy $1
copy "/mp3/"
copy $2
copy ".mp3"
end of regular expression
end of code

Note that there are no instructions for the limit_rate directive above as it is unrelated to thengx_http_rewrite_module module. A separate configuration is created for the if block. If the condition holds true, a request is assigned this configuration where limit_rate equals to 10k.

The directive

rewrite ^/(download/.*)/media/(.*)\..*$ /$1/mp3/$2.mp3 break;

can be made smaller by one instruction if the first slash in the regular expression is put inside the parentheses:

rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;

The corresponding instructions will then look like this:

match of regular expression
copy $1
copy "/mp3/"
copy $2
copy ".mp3"
end of regular expression
end of code

Module ngx_http_rewrite_module的更多相关文章

  1. Tengine 常用模块使用介绍

    Tengine 和 Nginx Tengine简介 从2011年12月开始:Tengine是由淘宝网发起的Web服务器项目.它在Nginx的基础上,针对大访问量网站的需求,添加了很多高级功能 和特性. ...

  2. 把www.domain.com均衡到本机不同的端口 反向代理 隐藏端口 Nginx做非80端口转发 搭建nginx反向代理用做内网域名转发 location 规则

    负载均衡-Nginx中文文档 http://www.nginx.cn/doc/example/loadbanlance.html 负载均衡 一个简单的负载均衡的示例,把www.domain.com均衡 ...

  3. centos 7 搭建 LNMP ( Linux+Nginx+MySQL+PHP )

    操作系统 | CentOS Linux release 7.6.1810 (Core) [root@localhost ~# cat /etc/redhat-release CentOS Linux ...

  4. 端口被占用通过域名的处理 把www.domain.com均衡到本机不同的端口 反向代理 隐藏端口 Nginx做非80端口转发 搭建nginx反向代理用做内网域名转发 location 规则

    负载均衡-Nginx中文文档 http://www.nginx.cn/doc/example/loadbanlance.html 负载均衡 一个简单的负载均衡的示例,把www.domain.com均衡 ...

  5. nginx学习笔记——http module分析

         源码:nginx 1.12.0           nginx由于其高性能.扩充性好等特点在迅速走红,越来越多的公司采用nginx作web服务器.负载均衡.waf等 工作,一些基于nginx ...

  6. Android Studio 编译单个module

    前期自己要把gradle环境变量配置好 在Terminal中gradle命令行编译apk 输入gradle assembleRelease 会编译全部module编译单个modulecd ./xiru ...

  7. ABP源码分析三:ABP Module

    Abp是一种基于模块化设计的思想构建的.开发人员可以将自定义的功能以模块(module)的形式集成到ABP中.具体的功能都可以设计成一个单独的Module.Abp底层框架提供便捷的方法集成每个Modu ...

  8. nodejs模块中exports和module.exports的区别

    通过Node.js的官方API可以看到Node.js本身提供了很多核心模块 http://nodejs.org/api/ ,这些核心模块被编译成二进制文件,可以require('模块名')去获取:核心 ...

  9. ES6之module

    该博客原文地址:http://www.cnblogs.com/giggle/p/5572118.html 一.module概述 JavaScript一直没有模块体系,但是伴随着ES6的到来,modul ...

随机推荐

  1. shell脚本——字符串

    printf printf "%-10s %-10s %-10s\n" NO Name    Height printf "%-10s %-10s %-10d\n&quo ...

  2. web开发: css高级与盒模型

    一.组合选择器 二.复制选择器优先级 三.伪类选择器 四.盒模型 五.盒模型显示区域 六.盒模型布局 一.组合选择器 <!DOCTYPE html> <html> <he ...

  3. 基于递归的BFS(Level-order)

    上篇中学习了二叉树的DFS深度优先搜索算法,这次学习另外一种二叉树的搜索算法:BFS,下面看一下它的概念: 有些抽象是不?下面看下整个的遍历过程的动画演示就晓得是咋回事啦: 了解其概念之后,下面看下如 ...

  4. 【JOISC2012】fish

    Description 有 \(n\) 条鱼,第 \(i\) 条鱼的长度为 \(L_i\),颜色是 \(C_i\)(\(C_i\) 只能是 'R','G','B'). 你需要从中挑出至少一条鱼,要求挑 ...

  5. sql server 安装

    第一次安装sql server是2016版本,因为[win7-64版系统配置比较低],所以不成功. 第二次安装2012版,在[数据库引擎配置]的时候,选择的是[添加当前用户],以及后续需要添加用户的时 ...

  6. mysql你问我答

    1.尊敬的先生,请您谈谈mysql数据库的引擎 数据库中的表设定了什么存储引擎,那么该表在数据存储方式.数据更新方式.数据查询性能以及是否支持索引等方面就会有不同的“效果”. mysql引擎大致分两类 ...

  7. $ python manage.py makemigrations You are trying to add a non-nullable field 'name' to course without a default; we can't do that (the database needs something to populate existing rows). Please selec

    问题: $ python manage.py makemigrationsYou are trying to add a non-nullable field 'name' to course wit ...

  8. 题解 【Uva】硬币问题

    [Uva]硬币问题 Description 有n种硬币,面值分别为v1, v2, ..., vn,每种都有无限多.给定非负整数S,可以选用多少个硬币,使得面值之和恰好为S?输出硬币数目的最小值和最大值 ...

  9. HDU 6098 - Inversion | 2017 Multi-University Training Contest 6

    /* HDU 6098 - Inversion [ 贪心,数论 ] | 2017 Multi-University Training Contest 6 题意: 求出所有B[i] = max(A[j] ...

  10. C++头文件中#pragma once与#ifndef……#define……#endif

    两者功能一样,防止重复包含被多次编译.建议头文件加入#pragma once C++头文件开头的两句与结尾的一句#ifndef <标识>#define <标识>类代码#endi ...