温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Nginx rewrite 企业实战操作

发布时间:2020-07-11 04:13:48 来源:网络 阅读:399 作者:哈哈怪1111 栏目:建站服务器

企业级rewrite 实战操作

Nginx rewrite 配置(文章由队员谆谆拟写)

我们的公共号

Nginx rewrite 企业实战操作

我们的 官网 https://wuguiyunwei.com

QQ群 602183872

相信大家在日常运维工作中如果你用到nginx作为前端反向代理服务器的话,你会对nginx的rewrite又爱又恨,爱它是因为你搞定了它,完成了开发人员的跳转需求后你会觉得很爽,觉得真的很强大,恨它是因为当一些稀奇古怪跳转的需求时候你会没有头绪、百般调试、上网求神拜佛都搞不定的时候真是想死的心都有了,当然网上也有很多nginx rewrite的经典示例,但是我感觉对我的工作都没有太大的帮助。下面是我工作中遇到的一些rewrite示例。提供给大家分享。

 

一、访问http://www.abc.com正常,现在需要访问abc.com,直接跳转到http://www.abc.com。

server {
listen 80;
server_name abc.com;
access_log off;
rewrite (.+) $scheme://www.$host$1 permanent;
}

二、如果你们域名是http://www.abc.com,现在想换一个域名http://www.def.com了,又不想失去之前域名的访问量,需要配置跳转。
首先需要在你的server_name里面把www.abc.com和www.def.cn都写上。
然后做如下配置:

location / {
if ($host = 'www.abc.com')
{
rewrite ^/(.*)$ http://www.def.com/$1 permanent;
}
}

三、跳转维护页面,比如今天维护,想挂一个维护页面,希望除某些特定的IP地址能正常访问,因为需要测试。其余所以的IP地址都是访问维护页面,这个需求我之前好像写过,但是今天写的有点不一样。在server里面添加如下内容:

set $rewrite true;
if ($remote_addr = "xxx.xxx.xxx.xxx") {
set $rewrite false;
}
if ($rewrite = true) {
rewrite (.+) http://www.abc.com/maintenance.html;
}
location = /maintenance.html {
  root /var/vhost;
}

四、比如现在你的域名是http://bbs.abc.com,现在将这个域名下面的帖子访问都跳转到http://www.abc.com/bbs,注意跳转后的参数也要保持一致。
比如:http://bbs.abc.com/post/addpost/913.shtml跳转到http://www.abc.com/bbs/post/addpost/913.shtml

location /post {
rewrite (.+) http://www.abc.com/bbs$1 permanent;
}

五、基于uri的跳转

if ($request_uri ~* ^/note\.php\?product_code=(.*)$) {
rewrite (.*) http://www.abc.com permanent;
}
if ($request_uri ~ ^/forum-(140|141|142|143|144|145|150|151|152|153|154|155|156|157|158|159|200|222|223|224|225|226|227|228)-(\d+).html$) {
rewrite (.*) http://www.abc.com/list permanent;
}

六、基于目录下面文件的跳转

location ~* /upload/.*\.php$ {
return 404;
}

七、最普通的url到url跳转

location ~* ^/ab/maintain/main.html {
rewrite (.+) http://www.abc.com/maintain/main.html permanent;
}

八、目录后的参数保持不变的跳转

rewrite ^/assets/upload/(.*)$ http://assets.kgc.cn/upload/$1 permanent;

九、多次匹配

if ($request_uri ~ ^/baseuiue(.shtml)|^/zhuanti/baseuiue(.shtml)) {
    rewrite (.+) http://123.abc.cn/zhuanti/baseuiue.shtml permanent;
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI