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.xml
、template-sitemap2.xml
等文件名。- 这样可以将两个
location
块合并成一个,更加简洁。
方案二:使用变量和 rewrite
location /template-sitemap {
rewrite ^/template-sitemap(\d+)\.xml1.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 new_uri {
~^/template-sitemap1.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
块更清晰地管理映射关系。
根据具体情况和需求,选择最适合的优化方案。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了