二、nginx URL重写[rewrite]
创始人
2024-02-09 21:24:04

一、URL重写

解释:URL重写是服务端干的事情,例如用户访问http://localhost/api其相当于访问/api的路由,URL重写可以把其转为其它路由处理如/api1.5或者用户访问/img下的图片,把其全部URL重写到/img/1.pngnginx可以用rewrite实现

格式:rewrite 当前访问路由的正则表达式 转向的内部路由(也可以是http开头的地址) 标志位

1.基础

        location /api {default_type text/plain;rewrite ^/api$ /look;   # 这里没有用标志位下面会用到} location /look {default_type text/plain;return 200 "hhhhh";}

2.标志位

  • last:遇到rewrite后不会执行下面的语句,而是跳转给对应的location执行
            location /api {default_type text/plain;rewrite ^/api$ /look;# 此处加上last得到的是“hhhhh”return 200 "1111";# 此时访问 /api 得到的是“1111”而不是“hhhhh”}location /look {default_type text/plain;return 200 "hhhhh";# 此时访问 /api 得到的是“1111”而不是“hhhhh”}
  • break:遇到rewrite后不会执行下面的语句,该标志将重写后的地址在当前的location块中执行(寻找root alias),不会将新的URI转向其他的location块(但是寻找的时候是新的URL)
        location /api {default_type text/plain;rewrite ^/api$ /look break;#此时该location没有配置root或者alias,其会去/usr/share/nginx/html/look寻找return 200 "1111";      # 不会被执行}  location /look {default_type text/plain;return 200 "hhhhh";}
  • redirect302临时重定向
  • permanent301永久重定向

二、应用

1.域名重定向

解释:例如访问http://baidu.com重定向到https://www.baidu.com

server {# 80跳转listen 80;server_name baidu.cn;rewrite (.*) https://www.baidu.cn$1 permanent;# $1是匹配前面正则括号,就是其访问的地址(不包括域名)
}

2.防盗链导向

解释:可以把所有图片导向一张图片

        location ~ /static/(image|img)/(.+)$ {alias /srv/flask/app/static/$1/$2;expires 172800;valid_referers ~.+\.baidu\.cn;if ($invalid_referer){rewrite (.*) /static/css/fang.svg;}}

相关内容

热门资讯

守护最北的日出星辰 转自:成都日报锦观江水深沉 江湾静谧守护最北的日出星辰 游客在漠河“神州北极”碑前打卡拍照,碑...
万华化学福建码头公司增资至10... 经济观察网 天眼查App显示,12月16日,万华化学(福建)码头有限公司发生工商变更,注册资本由4亿...
文旅“融”光焕发 共绘“诗与... ●兵团日报全媒体记者 姜蒙 通讯员 张培丽 胥强 仲冬时节,寒意渐浓,五师八十三团十连...
情暖援疆路 医心护健康 ●蔡伟 “医生,我的胃老是不舒服,吃了东西总不消化。”12月16日,在四师总医院可克达拉市院区...
以行践诺 服务暖心 ………… “我们将以更大力度推动‘万企兴万村’行动走深走实,团结引领兵团广大民营企业发挥优势,...