nginx rewrite

本文详细介绍了 Nginx 中 rewrite 指令的使用方法,包括语法、标志及实例。rewrite 指令能够根据正则表达式匹配请求 URI,并按指定方式改变 URI。文章还提供了配置示例,帮助读者更好地理解和应用该指令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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://” or “https://”, 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  breakdirective;
redirect
returns a temporary redirect with the 302 code; used if a replacement string does not start with “ http://” or “ https://”;
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 by break, 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.

 

 

1、http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值