15. nginx的rewrite模块
rewrite模块使用¶
- return指令
return code [text]; return code URL; return URL;
Nginx自定义 444 关闭链接 http1.0 301 永久重定向 302 临时重定向,禁止被缓存 http1.1 303 临时重定向,准许改变方法,禁止被缓存 307 临时重定向,不准许改变方法,禁止缓存
1、什么是301转向?什么是301重定向? 301转向(或叫301重定向,301跳转)是当用户或搜索引擎向网站服务器发出浏览请求时,服务器返回的HTTP数据流中头信息(header)中的状态码的一种,表示本网页永久性转移到另一个地址。 2、什么是302重定向? 302重定向又称之为302代表暂时性转移(Temporarily Moved ),英文名称:302 redirect。 也被认为是暂时重定向(temporary redirect),一条对网站浏览器的指令来显示浏览器被要求显示的不同的URL,当一个网页经历过短期的URL的变化时使用。一个暂时重定向是一种服务器端的重定向,能够被搜索引擎蜘蛛正确地处理。 3、301重定向与302重定向的区别 302重定向是暂时的重定向,搜索引擎会抓取新的内容而保留旧的网址。因为服务器返回302代码,搜索引擎认为新的网址只是暂时的。 301重定向是永久的重定向,搜索引擎在抓取新内容的同时也将旧的网址替换为重定向之后的网址。
- return指令与error_page
error_page code url error_page 404 /404.html
server {
server_name return.xxx.com;
listen 8080;
root html/;
error_page 404 /403.html;
return 403;
location / {
return 404 "find nothing";
}
}
url重写¶
语法 rewrite regex replacement[flag]; 将regex指定的url替换成replacement这个新的url,可以使用正则表达式来进行变量提取 当replacement以http://或https://或者$schema开头直接返回302重定向 替换后的url根据flag指定的方式进行处理 --last 用replacement这个url进行新的location匹配 --break 停止当前脚本的执行,等价于独立的break指令 --redirect 返回302重定向 --permanent 返回301重定向
cat rewrite.conf
server {
server_name rewrite.abc.com
rewrite_log on; #开启rewrite日志
error_log logs/rewrite_error.log notice;
location /first{
rewrite /first(.*) /second$1 last;
}
location /second{
#rewrite /second(.*) /third$1 ;
rewrite /second(.*) /third$1 break;
return 200 "second\n";
}
location /third {
return 200 "third\n";
}
location /redirect1 {
rewrite /redirect1(.*) $1 permanent;
}
location /redirect2 {
rewrite /redirect2(.*) $1 redirect;
}
location /redirect3 {
rewrite /redirect3(.*) http://rewrite.abc.com$1;
}
location /redirect4 {
rewrite /redirect4(.*) http://rewrite.abc.com$1 permanent;
}
}
[root@localhost html]# pwd
/usr/local/nginx/html
[root@localhost html]# tree
.
├── 50x.html
├── index.html
├── redirect1
│ └── index.html
├── redirect2
├── redirect3
└── third
└── 3.txt
4 directories, 4 files
curl rewrite.abc.com/first/3.txt 剩下的自动测试看结果
if 条件判断¶
语法:
if (condition) {}

- 实例
