/photos/123456
为:
/path/to/photos/12/1234/123456.png
则使用以下正则表达式(注意引号):
rewrite "/photos/([0-9] {2})([0-9] {2})([0-9] {2})" /path/to/photos/$1/$1$2/$1$2$3.png;
如果指定一个“?”在重写的结尾,Nginx将丢弃请求中的参数,即变量$args,当使用$request_uri或$uri&$args时可以在rewrite结尾使用“?”以避免nginx处理两次参数串。
在rewrite中使用$request_uri将www.example.com重写到example.com:
server { server_name www.example.com; rewrite ^ http://example.com$request_uri? permanent;}
同样,重写只对路径进行操作,而不是参数,如果要重写一个带参数的URL,可以使用以下代替:
if ($args ^~ post=100){ rewrite ^ http://example.com/new-address.html? permanent;}
注意$args变量不会被编译,与location过程中的URI不同(参考http核心模块中的location)。
rewrite_log
语法:rewrite_log on | off
默认值:rewrite_log off
使用字段:server, location, if
变量:无
启用时将在error log中记录notice 标记的重写日志。
set
语法:set variable value
默认值:none
使用字段:server, location, if
指令设置一个变量并为其赋值,其值可以是文本,变量和它们的组合。
你可以使用set定义一个新的变量,但是不能使用set设置$http_xxx头部变量的值。
uninitialized_variable_warn
语法:uninitialized_variable_warn on|off
默认值:uninitialized_variable_warn on
使用字段:http, server, location, if
开启或关闭在未初始化变量中记录警告日志。
事实上,rewrite指令在配置文件加载时已经编译到内部代码中,在解释器产生请求时使用。
这个解释器是一个简单的堆栈虚拟机,如下列指令:
location /download/ { if ($forbidden) { return 403; } if ($slow) { limit_rate 10k; } rewrite ^/(download/.*)/media/(.*)\..*$ /$1/mp3/$2.mp3 break;
将被编译成以下顺序:
variable $forbiddenchecking to zerorecovery 403completion of entire codevariable $slowchecking to zerocheckings of regular excodessioncopying "/"copying $1copying "/mp3/"copying $2copying ".mp3"completion of regular excodessioncompletion of entire sequence
注意并没有关于limit_rate的代码,因为它没有提及ngx_http_rewrite_module模块,“if”块可以类似”location”指令在配置文件的相同部分同时存在。
如果$slow为真,对应的if块将生效,在这个配置中limit_rate的值为10k。
指令:
rewrite ^/(download/.*)/media/(.*)\..*$ /$1/mp3/$2.mp3 break;
如果我们将第一个斜杠括入圆括号,则可以减少执行顺序:
rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
之后的顺序类似如下:
checking regular excodessioncopying $1copying "/mp3/"copying $2copying ".mp3"completion of regular excodessioncompletion of entire code