nginx地址重写
【nginx地址重写】
nginx rewrite技术主要实现URL地址重写,且支持正则表达式。
rewrite 能够实现URL的跳转,需要nginx在编译安装的时候,装好PCRE这个软件。
通过rewrite可以规范URL、根据变量进行URL跳转等,常用的功能如
1.对于爬虫的封禁,让其跳转无用页面
2.动态的URL伪装成HTML页面,便于搜索引擎的抓取
3.旧域名、旧目录的更新,需要跳转到新的URL地址
【语法】
rewrite ^/(.*) http://192.168.178.134/$1 permanent;
#解释
rewrite是指令,开启一个跳转规则
正则是 ^/(.*) 表示匹配所有,匹配成功后跳转到后面的url地址
$1 表示取出前面正则括号里的内容
permanent表示 301 重定向的标记
rewrite的结尾参数flag标记
last 规则匹配完成后,继续向下新的location
break 本条规则完成匹配后,立即停止
redirect 返回302临时重定向,浏览器地址栏显示跳转后的URL
permanent 返回301永久重定向,浏览器地址显示跳转后的URL
ps:last和break用于实现URL重写,浏览器地址栏不发生变化
redirect和permanent用于实现URL跳转,浏览器地址栏跳转新的URL
【实现301跳转】
#请求直接跳转到百度
[root@backup ~]# vim /opt/tngx232/conf/extra/nginx_rewrite.conf
server {
listen 90;
server_name _;
rewrite ^/(.*) http://www.baidu.com/$1 permanent;
}
[root@backup ~]# nginx -t
nginx: the configuration file /opt/tngx232/conf/nginx.conf syntax is ok
nginx: configuration file /opt/tngx232/conf/nginx.conf test is successful
[root@backup ~]# nginx -s reload
[root@backup ~]# curl 10.0.0.200:90
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>301 Moved Permanently</title></head>
<body>
<center><h1>301 Moved Permanently</h1></center>
<hr/>Powered by Tengine/2.3.2<hr><center>tengine</center>
</body>
</html>
用浏览器进行测试