注意:每次做完一个需要将前面的配置文件中配置清除,防止影响结果
一、应用场景——基于域名的跳转
1、公司旧域名www.accp.com,因业务需求有变更,
需要使用新域名www.kgc.com代替
1)不能废除旧域名
2)从旧域名跳转到新域名,且保持其参数不变
[root@localhost ~]vim /etc/nginx/comf.d/default.conf
listen 80;
server_name www.accp.com; #域名修改
#charset koi8-r;
access_log /var/log/nginx/www.accp.c0m-access.log main;
location / {
#域名重定向
if ($host = 'www.accp.com') {
rewrite ^/(.*)$ http://www.kgc.com/$1 permanent;
}
root /usr/share/nginx/html;
index index.html index.htm;
}
[root@localhost ~]# systemctl reload nginx
浏览器输入模拟访问http://www.accp.com/test/1/index.php(虽然这个请求内容 是不存在的),会自动跳转到http://www.kgc.com/test/1/index.php,从headers里面可以看到301实现了永久重定向跳转,而且域名后的参数也正常跳转。
二、应用场景——基于客户端IP访问跳转
公司业务版本上线,所有IP访问任何内容都显示一个固定维护页面,只有公司IP访问正常
所有IP访问任何内容都显示一个固定维护页面,只有公司 IP:192.168.154.177访问正常。
[root@localhost ~]vim /etc/nginx/conf.d/default.conf
listen 80;
server_name www.accp.com;
#charset koi8-r;
access_log /var/log/nginx/www.accp.com-access.log main;
set $rewrite true;
if ($remote_addr = "192.168.154.177") {
set $rewrite false;
}
if ($rewrite = true) {
rewrite (.+)/main.html;
}
location = /main.html {
root /usr/share/nginx/html;
}
[root@localhost ~]# echo "<h1>this is web</h1>" > /usr/share/nginx/html/main.html
所有IP用户(除IP :192.168.154.177的用户)访问网址都显示以下页面
三、应用场景——基于旧、新域名跳转并加目录
将域名http://bbs.accp.com/post下面的发帖都跳转到http://www.kgc.com/bbs/post,且域名跳转后保持参数不变
[root@localhost ~]vim /etc/nginx/conf.d/default.conf
listen 80;
server_name bbs.accp.com;
#charset koi8-r;
access_log /var/log/nginx/www.accp.com-access.log main;
location /post {
rewrite (.+) http://www.accp.com/bbs$1 permanent;
}
[root@localhost ~]# systemctl reload nginx
注意:accp.com.zone 需要更改主机名解析,把www 改为 bbs
四、应用场景——基于参数匹配的跳转
浏览器访问
http://www.accp.com/100-(100|200)-100.html
跳转到http://www.accp.com页面
[root@localhost ~]vim /etc/nginx/conf.d/default.conf
listen 80;
server_name www.accp.com;
#charset koi8-r;
access_ log /var/log/nginx/www.accp.com-access.log main;
if ($request_uri ~ ^/100-(100|200)-(\d+).html$) {
rewrite (.*) http://www.accp.com permanent ;
}
[root@localhost ~]# systemctl restart nginx
浏览器输入模拟访问
http://www.accp.com/100-100-100.html
自动跳转到www.accp.com
五、应用场景——基于目录下所有php文件跳转
访问http://www.accp.com/upload/1.php跳转到首页
[root@localhost ~]vim /etc/nginx/conf.d/default.conf
listen 80;
server_name www.accp.com;
#charset koi8-r;
access_ log /var/log/nginx/www.accp.com-access.log main;
location ~* /upload/.*\.php$ {
rewrite (.+) http://www.accp.com permanent;
}
[root@localhost ~]# systemctl restart nginx
浏览器输入模拟访问
http://www.accp.com/upload/1.php
自动跳转到www.accp.com
六、应用场景——基于最普通url请求的跳转
访问一个具体的页面跳转到首页
[root@localhost ~]vim /etc/nginx/conf.d/default.conf
listen 80;
server_name www.accp.com;
#charset koi8-r;
access_ log /var/log/nginx/www.accp.com-access.log main;
location ~* ^/abc/123.html {
rewrite (.+) http://www.accp.com permanent;
}
[root@localhost ~]# systemctl restart nginx
浏览器输入模拟访问
http://www.accp.com/abc/123.html
自动跳转到www.accp.com