rewrite就是重定向, 就是将接收到的请求依据配置规则重定向称为另一个请求返回; 实际使用中非常方便,比如消息转发, 错误页面的处理等; nginx的ngx_http_rewrite_module模块实现了对URL的判断,正则,重定向;
基本指令:
- break: 停止执行当前虚拟主机的后续 rewrite 指令集;
- if: 对给定条件condition进行判断, 如果为真,则执行大括号内的rewrite指令;
# 根据nginx提供的变量或模块提供的变量来判断,产生对应动作;
server {
listen 80;
server_name www.cc.com;
access_log logs/cccom/access_log main;
error_log logs/cccom/error.log;
location / {
if ($http_user_agent != MSIE) {
return 403;
}
root html/cccom;
index index.html;
}
}
- return: 用来停止处理并返回状态或URL;
- set: 创建自定义变量;
set variable value; - rewrite: 重定向至其他URL中; Syntax:
rewrite regex replacement [flag];partment如果一个URI匹配指定的正则表达式regex, URI就按照replacement重写;
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.
演示:
# 检测rewrite和return的执行顺序;
server{
listen 80;
server_name www.cc.com;
access_log logs/cccom/access_log main;
error_log logs/cccom/error.log;
location / {
if ($http_user_agent != MSIE) {
return 403;
}
root html/cccom;
index index.html;
}
location /one {
rewrite /one/(.*) /two/$1;
#return 200 'hello one';
}
location /two {
rewrite /two/(.*) http://www.cloud1908.com/three/$1 permanent;
#return 200 'hello two';
}
location /three {
return 200 "hello third";
}
}
实例: 防止SQL注入的rewrite使用功能
# 通过判断URI中是否有 ’ ; > < 等字符可以快速过滤掉可能发生SQL注入的请求,然后直接返回"404 Not Found"
# http://www.c.com/login.php?param01=`create`¶m02=`database`¶m=`dq;` -> query_string
if ( $uri ~* ".*[;`<>].*" ) {
return 404;
}
实例: 当用户访问的资源不存在时,直接重定向至自定义页面
location / {
root html;
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^(.*)$ /notfound.html break;
}
}
location / {
root html;
index index.html index.htm;
if (!-e $request_filename) {
rewrite ^(.*)$ /notfound.html break;
}
}








网友评论