## Rewrite规则
rewrite功能就是,使用nginx提供的全局变量或自己设置的变量,结合正则表达式和标志位实现url重写以及重定向。rewrite只能放在server{},location{},if{}中,并且只能对域名后边的除去传递的参数外的字符串起作用,例如`http://seanlook.com/a/we/index.php?id=1&u=str`只对/a/we/index.php重写。语法`rewrite regex replacement [flag];`
如果相对域名或参数字符串起作用,可以使用全局变量匹配,也可以使用proxy\_pass反向代理。
表明看rewrite和location功能有点像,都能实现跳转,主要区别在于rewrite是在同一域名内更改获取资源的路径,而location是对一类路径做控制访问或反向代理,可以proxy\_pass到其他机器。很多情况下rewrite也会写在location里,它们的执行顺序是:
1. 执行server块的rewrite指令
2. 执行location匹配
3. 执行选定的location中的rewrite指令
如果其中某步URI被重写,则重新循环执行1-3,直到找到真实存在的文件;循环超过10次,则返回500 Internal Server Error错误。
## write实例
~~~bash
http {
# 定义image日志格式
log_format imagelog '[$time_local] ' $image_file ' ' $image_type ' ' $body_bytes_sent ' ' $status;
# 开启重写日志
rewrite_log on;
server {
root /home/www;
location / {
# 重写规则信息
error_log logs/rewrite.log notice;
# 注意这里要用‘’单引号引起来,避免{}
rewrite '^/images/([a-z]{2})/([a-z0-9]{5})/(.*)\.(png|jpg|gif)$' /data?file=$3.$4;
# 注意不能在上面这条规则后面加上“last”参数,否则下面的set指令不会执行
set $image_file $3;
set $image_type $4;
}
location /data {
# 指定针对图片的日志格式,来分析图片类型和大小
access_log logs/images.log mian;
root /data/images;
# 应用前面定义的变量。判断首先文件在不在,不在再判断目录在不在,如果还不在就跳转到最后一个url里
try_files /$arg_file /image404.html;
}
location = /image404.html {
# 图片不存在返回特定的信息
return 404 "image not found\n";
}
}
~~~
- 简介
- 【入门】并发特性
- 【入门】安装启动
- 【入门】基础必会
- 【基础】正向代理
- 【基础】反向代理
- 【基础】动静分离
- 【基础】负载均衡
- 【基础】HTTP服务器
- 【应用】配置一键生成
- 【应用】乱码处理
- 【应用】开启目录浏览功能
- 【应用】错误码原因和解决方案
- 【应用】location用法
- 【应用】常用正则
- 【应用】rewrite
- 【应用】全局变量
- 【应用】if用法
- 【应用】配置https
- 【应用】PHP-fastcgi
- 【应用】flag标志位
- 【应用】过期功能
- 【应用】gzip压缩
- 【应用】会话保持
- 【应用】worker最大打开文件数
- 【应用】sendfile传输文件
- 【应用】单进程最大连接数
- 【应用】事件驱动
- 【应用】隐藏版本号
- 【应用】网络连接优化
- 【应用】缓存机制
- 【应用】网络限流
- 【应用】日志配置
- 【应用】灰度发布
- 【关于】作者