#Rewrite基本概述
1.什么是rewrite
rewrite即url重写,主要实现url地址重写,以及重定向,就是把传入的Web请求重定向到其他URL的过程。
2.Rewrite使用场景
1.URL地址跳转。例如用户访问old.com将其跳转到oldboy.com,或者当用户通过http的方式访问odl.com是将其跳转至https的方式访问oldboy.com
2.URL伪静态,将动态页面显示 为静态页面方式的一种技术,以便于搜索引擎的录入,同时减少动态URL对外暴露过多的参数,提升更高的安全性。
3.搜索引擎SEO优化依赖于URL路径,以便支持搜索引擎录入
4.可以调整用户浏览的URL,看起来更规范,合乎开发及产品人员的需求。
Nginx常用的一些变量
变量 含义 示例
$request 整个请求行 GET /nginx-var/request-line?a=1&b=2 HTTP/1.1
$request_method 请求方法(如GET、POST) GET
$request_uri 完整的请求URI /nginx-var/request-line?a=1&b=2
$uri URI,除去查询字符串 /nginx-var/request-line
d
o
c
u
m
e
n
t
u
r
i
同
document_uri 同
documenturi同uri /nginx-var/request-line
$args 查询字符串 a=1&b=2
q
u
e
r
y
s
t
r
i
n
g
同
query_string 同
querystring同args a=1&b=2
$server_protocol 请求协议(如HTTP/1.0 HTTP/1.1) HTTP/1.1
$arg_name 请求行中name参数的值 $arg_a = 1 , $arg_b = 2
#Rewrite配置语法
Rewrite示例
Syntax: rewrite regex replacement [flag];
Default: —
Context: server, location, if
Rewrite匹配优先级
1.执行server块的rewrite指令
2.执行location匹配
3.执行选定的location中的rewrite
开启Nginx的Rewrite日志功能
vim /etc/nginx/nginx.conf
1.设置nginx的错误日志级别为notice
error_log /var/log/nginx/error.log notice;
2.在http模块层,增加一行rewrite_log日志
http{
rewrite_log on;
}
3.配置
server {
listen 80;
server_name rewrite.test.com;
root /home/www;
index index.html index.php index.htm;
location ~* /ad/aa.html {
rewrite /ad/aa.html /www1/index.html;
access_log /var/log/nginx/rewrite/access.log;
}
}
配置优化
server {
listen 80;
server_name rewrite.test.com;
root /home/www;
index index.html index.php index.htm;
location ~* /ad/aa.html {
rewrite 。* /www1/index.html;
access_log /var/log/nginx/rewrite/access.log;
}
}
优化配置302
server {
listen 80;
server_name rewrite.test.com;
root /home/www;
index index.html index.php index.htm;
location ~* /ad/aa.html {
#rewrite .* /www1/index.html;
rewrite .* /www1/index.html redirect;
return 302 /www1/index.html;
效果一样都是跳转重定向,不要一起配置,只能配置一个
}
}
显示出响应码为302 url地址会变化
配置优化:
http://rewrite.test.com/ad/index.html --> http://rewrite.test.com/www1/index.html
server {
listen 80;
server_name rewrite.test.com;
root /home/www;
index index.html index.php index.htm;
location ~* /ad {
#rewrite .* /www1/index.html;
#return 302 /www1/index.html;
rewrite ^/ad/(.*)$ /www1/$1 redirect;
}
}
例子:用户访问/test目录下任意内容,实际上真实服务的是https://www.baidu.com/
location ~* /test {
rewrite (.*) https://www.baidu.com/ redirect;
}
例子:用户访问/zz/www-11-22-33.html实际上真实访问的是www1/11/22/33/index.html
http://rewrite.test.com/zz/www-11-22-33.html -->http://rewrite.test.com/www1/11/22/33/index.html
location ~* /zz {
rewrite www-(.*)-(.*)-(.*).html /www1/$1/$2/$3/index.html redirect;
}
例子:
将http请求,跳转至https
rewrite ^(.*) https://$server_name$1 redirect;
或者
return 302 https://$request_uri;
3.Rewrite标记Flag
rewrite指令根据表达式来重定向URI,或者修改字符串。可以应用于server,location,if环境下,每行rewrite指令最后跟一个flag标记,支持的flag标记有如下表格所示。
redirect:返回302临时重定向,浏览器地址栏会显示跳转后的URL地址,爬虫不会更新URL
permanent:返回301永久重定向,浏览器地址栏会显示跳转后的URL地址,爬虫会更新URL
break:停止处理后续rewrite指令集,不会跳出location作用域,不再进行重新查找,终止匹配,URL地址不变
last:停止处理后续rewrite指令集,跳出location作用域,并开始搜索与更改后的URI相匹配的location,URL地址不变