nginx反向代理配置,使用正则,三种方案

方案一:使用变量和通配符

location ~ ^/(template-sitemap\d+\.xml)$ {
  proxy_pass https://cdn.processon.io/sitemap/$1;

解释:

  • ~ 表示使用正则表达式匹配。
  • ^/(template-sitemap\d+\.xml)$ 匹配以 /template-sitemap 开头,后跟一个或多个数字(\d+),然后以 .xml 结尾的路径。
  • $1 表示正则表达式中第一个捕获组的内容,即匹配到的 template-sitemap1.xmltemplate-sitemap2.xml 等文件名。
  • 这样可以将两个 location 块合并成一个,更加简洁。

方案二:使用变量和 rewrite

location /template-sitemap {
  rewrite ^/template-sitemap(\d+)\.xml$ /sitemap/template-sitemap$1.xml break;
proxy_pass https://cdn.processon.io;
}

解释:

  • rewrite 指令将 /template-sitemap1.xml/template-sitemap2.xml 重写为 /sitemap/template-sitemap1.xml/sitemap/template-sitemap2.xml
  • break 选项表示停止当前 location 块的处理,将请求传递给 proxy_pass 指定的地址。

方案三:使用 map

map $uri $new_uri {
  ~^/template-sitemap1.xml$ https://cdn.processon.io/sitemap/template-sitemap1.xml;
  ~^/template-sitemap2.xml$ https://cdn.processon.io/sitemap/template-sitemap2.xml;
}

server {
  location ~ ^/template-sitemap\d+\.xml$ {
  proxy_pass $new_uri;
  }
}

解释:

  • map 块定义了一个变量 $new_uri,根据 $uri 的不同值映射到不同的目标地址。
  • location 块中,使用正则表达式匹配 /template-sitemap\d+\.xml,并通过 proxy_pass 指令使用 $new_uri 变量来代理请求。

选择适合的方案

  • 方案一 适合只有少量相似路径需要代理的情况,简单直接。
  • 方案二 可以处理更多复杂的重写规则,灵活性较高。
  • 方案三 对于更多的路径映射,可以通过 map 块更清晰地管理映射关系。

根据具体情况和需求,选择最适合的优化方案。

posted @ 2024-07-24 14:26  GaoYanbing  阅读(3)  评论(0编辑  收藏  举报