首页 > 解决方案 > NGINX - 基于查询参数的不同后端代理

问题描述

我有一个特殊的场景,我需要根据查询参数路由到不同的后端:

https://edge1.cdn.com/file.zip?{secure_link}&{tokens}&route=aws1

aws1 在哪里说http://edge1.amazonwebservices.com

如果它的 aws2 那么代理后端将是http://edge2.amazonwebservices.com

等等......但我仍然没有弄清楚如何做到这一点。

标签: nginxproxyreverse-proxy

解决方案


您可以使用map指令从$arg_route变量(包含route查询参数的值)中获取代理主机名:

map $arg_route $aws {
    aws1    edge1.amazonwebservices.com;
    aws2    edge2.amazonwebservices.com;
    ...
    default <default_hostname>;
}

server {
    ...
    # if you want to proxy the request, you'd need a 'resolver' directive
    resolver <some_working_DNS_server_address>;

    location / {
        # if you want to proxy the request
        proxy_pass http://$aws;
        # or if you want to redirect the request
        rewrite ^ http://$aws$uri permanent;
    }
}

如果您不想在没有route查询参数的情况下为请求提供服务,则可以省略该块的最后default一行map并将以下if块添加到您的服务器配置中:

if ($aws = '') {
    return 403; # HTTP 403 denied
}

如果您需要代理请求,您还需要一个指令(您可以在本文resolver中阅读有关它的一些技术细节)。


推荐阅读