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+)\.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块更清晰地管理映射关系。
根据具体情况和需求,选择最适合的优化方案。

浙公网安备 33010602011771号