二、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;}}

相关内容

热门资讯

豆神教育:董事长窦昕辞职 唐颖... 3月23日,豆神教育(维权)(300010)发布公告,董事长窦昕因工作安排调整辞去董事长及非独立董事...
RadexMarkets瑞德克... 3月23日,近期,加密货币市场在关键周线收官之际遭遇剧烈波动,比特币价格在周末跌破69000美元关口...
吉林省一地拍到“巨鸟”过马路,... (来源:长春相遇)老铁别急!“座山雕”国道溜达,东北大哥大姐齐让路老话说得好,“春江水暖鸭先知”,可...
03月23日 美元兑泰铢跌破3... Hehson外汇消息2026年03月23日,截至19时31分,外汇市场上美元兑泰铢汇率跌破1美元兑换...
冠石科技2025年报解读:净亏... 营业收入:微增0.44%,内部结构分化明显2025年冠石科技实现营业收入13.65亿元,较上年同期的...