在Nginx配置中,proxy_pass指令常与正则表达式配合使用来实现灵活的反向代理功能。本文将详细介绍如何使用正则表达式提取变量并在proxy_pass中应用这些变量。
Nginx支持在location块中使用正则表达式,语法如下:
location ~ ^/user/(\d+)/profile$ {
# 使用$1引用第一个捕获组
proxy_pass http://backend/user_$1;
}
Nginx 1.11.2+版本支持命名捕获组,语法更清晰:
location ~ ^/user/(?\d+)/profile$ {
# 使用$user_id引用命名捕获组
proxy_pass http://backend/user_$user_id;
}
以下示例展示如何代理多级路径:
location ~ ^/api/(v\d+)/(.*)$ {
# $1对应版本号,$2对应剩余路径
proxy_pass http://api_backend/$1/$2;
}
这种技术常用于: