重写的规则可以放在 serverer 里,也可以放在 location 里。
rewrite 规则:
常用的命令有
① if(条件){} 设定条件,再进行重写
if 语法:
if 空格 (条件){
重写模式
}
条件的写法:
a.“=”来判断相等,用于字符串比较
b.“~”用正则来匹配(此处正则区分大小写)
“~*”表示此处正则不区分大小写
c.-f -d -e 分别判断是否为文件、为目录、是否存在
【例】测试 if 和 return(= 相等)
在 /usr/local/nginx/html/ 下创建新文件 test-if.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>rewrite example-if and return</title>
<body>
test if and return.
</body>
</head>
</html>
访问 http://192.168.254.100/test-if.html,显示:

查看访问日志
[root@localhost nginx]# tail logs/access.log:

(附:Chrome、FF、IE 的信息中都带有Mozilla/5.0,是90年代网景公司 Netscape 流行导致的历史问题,真正的浏览器内核版本要看最后,例如 ff 是Gecko/20100101 Firefox/39.0)
编辑 /usr/local/nginx/conf/nginx.conf
[root@localhost nginx]# vim conf/nginx.conf
在
location / {
root html;
index index.html index.htm;
}
中进行重写:
location / {
if ($remote_addr = 192.168.254.1){
return 403;
}
root html;
index index.html index.htm;
}
即当客户端的 ip 是 192.168.254.100 时,返回 403 状态码
平滑重启 nginx
访问 http://192.168.254.100/test-if.html,显示

【例】 测试 if 和 rewrite (正则表达式),匹配 ie 用户(User-Agent头信息中是否含有 Trident)
注释上例中的 rewrite
location / {
if ($http_user_agent ~* Trident){
rewrite ^.*$ /ie.html;
break;
}
root html;
index index.html index.htm;
}
注意:如果不加 break,则会报 500 错误,表示无限重定向
平滑重启 nginx
在 /usr/local/nginx/html 下新建文件 ie.html,所有的 ie 用户统统访问该页面
[root@localhost nginx]# vim html/ie.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ie用户看到的页面</title>
<body>
请不要使用 IE浏览器 :)
</body>
</head>
</html>
此时使用 IE 11 访问http://192.168.254.100/test-if.html,显示:

使用 ff 访问该页面,显示:

在 /usr/local/nginx/logs/access.log 中,IE、ff、Chrome 访问该页面的信息分别如下:
IE

ff

chrome

chrome 显示:

【例】-f -d -e 分别判断是否为文件、为目录、是否存在
首先使用 rewrite 实现当文件不存在时显示 404 页面
在 /usr/local/nginx/html 下新建 404.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>404页面</title>
<body>
404 Not Found
</body>
</head>
</html>
编辑 /usr/local/nginx/conf/nginx.conf
(nginx 引用的变量可以在 /usr/local/nginx/conf/fastcgi.conf 中找到,其中fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 表示访问的当前页面)
location / {
if ($http_user_agent ~* Trident){
rewrite ^.*$ /ie.html;
break;
}
if (!-e $document_root$fastcgi_script_name){
rewrite ^.*$ /404.html;
break;
}
root html;
index index.html index.htm;
}
平滑重启 nginx
访问一个不存在的页面:http://192.168.254.100/dee.html,显示:

此时的访问日志:

说明此时访问的仍然是 dee.html,而不是 404.html,因此在 rewrite 时仍然要写 break。
② set #设置变量
可以在多条件判断时做标记用,相当于 apache 的 rewrite_condition(重写条件)
【例】使用 set 来实现 IE 用户访问任意页面都跳转到 ie.html 页面
注释之前在 location 中的配置,并在 location 中添加配置,此时的 location 信息为:
location / {
if ($http_user_agent ~* Trident){
set $isie 1;
}
if ($fastcgi_script_name = ie.html){
set $isie 0;
}
if ($isie = 1){
rewrite ^.*$ ie.html;
}
root html;
index index.html index.htm;
}
平滑重启 nginx
此时分别用 ie 和 ff 访问 http://192.168.254.100/test-if.html,分别显示:

③ return #返回状态码
④ break #跳出 rewrite
⑤ rewrite #重写
















