使用 “rewrite 旧地址 新地址 [redirect]”,来让地址重定向,其中redirect为可选项,表示浏览器地址栏的url是否发生变化。
例1:访问www.a.com/a.html------->www.a.com/b.html
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80; #端口
server_name www.a.com; #虚拟主机
rewrite /a.html /b.html; #www.a.com/a.html www.a.com/b.html
location / {
root html; # documentRoot
index index.html index.htm; # 默认是index.html页面
}
}
还需要配置域名www.a.com,可以通过配置dns或者修改/etc/hosts
例2:访问192.168.4.20------->www.baidu.com
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80; #端口
server_name localhost; #虚拟主机
rewrite ^/ http://www.baidu.com; #其中^代表正则表达式,^/表示所有路径
location / {
root html; # documentRoot
index index.html index.htm; # 默认是index.html页面
}
}
例3:访问192.168.4.20/xxxxx------->www.baidu.com/xxxxx
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80; #端口
server_name localhost; #虚拟主机
rewrite ^/(.*) http://www.baidu.com/$1; #其中^代表正则表达式,^/(.*)表示提取所有路径,然后通过$1使用匹配到的路径
location / {
root html; # documentRoot
index index.html index.htm; # 默认是index.html页面
}
}
例4:实现不同的浏览器访问192.168.4.20/test.html返回不同的页面
这里咱们使用curl浏览器和firefox浏览器。curl是一款没有图形的浏览器,只可以显示代码信息。
首先看配置文件:
然后看登录日志 /usr/local/nginx/logs/access.log
xxx.xx.xxx.xx - - [20/Sep/2019:23:08:54 +0800] “GET /poweredby.png HTTP/1.1” 404 555 “http://xx.xx.xx.xx/” “Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36”
其中配置文件的变量$http_user_agent 对应日志中的
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
Safari代表浏览器的类型。
因此只需要在配置文件中让变量 $http_user_agent 和对应的浏览器进行模糊匹配就可以了
if ($http_user_agent ~* firefox) { # 其中~代表正则,*代表忽略大小写,注意if后的空格
rewrite ^/(.*) /firefox/$1; # 同案例3
}
mkdir /var/local/nginx/html/firefox
echo 'firefox page!!' > /var/local/nginx/html/firefox/test.html
echo 'normal page!!!!' > /var/local/nginx/html/test.html
重启niginx服务。nginx -s reload
写总结的第十六天!!!