六、地址重写(地址栏重写)
rewrite 旧地址 新地址 [选项];
选项:
last 不再读其他 break 不再读其他语句,结束请求
redirect 临时重定向 permament 永久重定向 (临时与永久设置需准确,否则容易被蜘蛛丢弃)
访问a.html重定向到b.html(地址栏不变)
配置:
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf //修改Nginx服务配置
.. ..
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
rewrite /a.html /b.html;
}
}
[root@proxy ~]# echo "BB" > /usr/local/nginx/html/b.html
起服务、验证:
/usr/local/nginx/sbin/nginx -s reload
firefox http://192.168.4.5/a.html
访问a.html重定向到b.html(跳转地址栏)
配置:
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf //修改Nginx服务配置
.. ..
server {
listen 80;
server_name localhost;
charset utf-8; //设置语言格式,utf-8 页面可以识别中文
location / {
root html;
index index.html index.htm;
rewrite /a.html /b.html redirect;
}
}
起服务:
/usr/local/nginx/sbin/nginx -s reload
测试:(仔细观察浏览器地址栏的变化)
firefox http://192.168.4.5/a.html
修改配置文件(访问192.168.4.5的请求重定向至www.tmooc.cn)
配置:
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
.. ..
server {
listen 80;
server_name localhost;
rewrite ^/ http://www.tmooc.cn; //访问到该ip以根开头 跳转到http://www.tmooc.cn
location / {
root html;
index index.html index.htm;
# rewrite /a.html /b.html redirect;
}
}
起服务:
[root@proxy ~]# /usr/local/nginx/sbin/nginx -s reload
测试:(真实机测试,真实机才可以连接tmooc)
[root@room9pc01 ~]# firefox http://192.168.4.5
修改配置文件(访问192.168.4.5/下面子页面,重定向至www.tmooc.cn/下相同的页面)
配置:
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
.. ..
server {
listen 80;
server_name localhost;
rewrite ^/(.*)$ http://www.tmooc.cn/$1; //正则表达式
location / {
root html;
index index.html index.htm;
# rewrite /a.html /b.html redirect;
}
}
起服务:
[root@proxy ~]# /usr/local/nginx/sbin/nginx -s reload
测试:(真实机测试,真实机才可以连接tmooc)
[root@room9pc01 ~]# firefox http://192.168.4.5
[root@room9pc01 ~]# firefox http://192.168.4.5/test
修改配置文件(实现curl和火狐访问相同链接返回的页面不同)
创建页面----配置----起服务---测试
创建页面:
[root@proxy ~]# echo "I am Normal page" > /usr/local/nginx/html/test.html
[root@proxy ~]# mkdir -p /usr/local/nginx/html/firefox/
[root@proxy ~]# echo "firefox page" > /usr/local/nginx/html/firefox/test.html
配置:
[root@proxy ~]# vim /usr/local/nginx/conf/nginx.conf
.. ..
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
if ($http_user_agent ~* firefox) { //识别客户端firefox浏览器, ~符号代表正则匹配,*符号代表不区分大小写
rewrite ^(.*)$ /firefox/$1;
}
}
起服务、验证:
[root@proxy ~]# /usr/local/nginx/sbin/nginx -s reload
[root@client ~]# firefox http://192.168.4.5/test.html
[root@client ~]# curl http://192.168.4.5/test.html