nginx学习-ngx_http_rewrite_module模块

306 阅读1分钟

return 指令

我们看官方手册的说明:

Syntax:	return code [text];
return code URL;
return URL;
Default: —
Context: server, location, if
location ~ (.*).js$ {
   return 500;  #返回500状态码
}

location ~ (.*).js$ {
   return 500 "error"; #返回500状态码 同时打印error
}

location ~ (.*).js$ {
   return 302 http://www.baidu.com; # 302状态码,跳转到百度
}

注意当使用 return url 指令操作的时候,只能使用302(临时重定向) 301(永久重定向) 类似跳转,而不能使用500或其他状态码。

rewrite 指令

rewrite 指令是一个常用的指令,根据访问url定位真实地址

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

下面表示当访问地址以 .js 后缀开头的时候

如果匹配正则表达式成功,就直接重写到js目录下。

location ~ (.*).js$ {
    rewrite (.*) /js/$1 break;
}

注意这个js的目录地址, 是相对于root指定的目录为根目录寻找的。 rewrite第三个参数为break,表示中断,不再继续向下执行.

rewrite第三个参数取值:

last
   使用了last 指令,rewrite 后会跳出location
break
   使用break直接终止继续进行匹配
redirect
    表示302临时重定向
permanent
    表示301永久重定向

是否记录 rewrite_log

Syntax:	rewrite_log on | off;
Default: rewrite_log off;
Context:http, server, location, if

if条件判断

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

下面是一些常用的判断示例

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