skip to Main Content

I have the following map based on the value of a cookie:

map $cookie_version $version_host {
    default 172.17.0.1:8001;
    2.65.1 172.17.0.1:8001;
    2.65.2 172.17.0.1:8003;
}

However I need the same map for the value of a header:

map $http_app_version $version_api_host {
    default 172.17.0.1:8001;
    2.65.1 172.17.0.1:8001;
    2.65.2 172.17.0.1:8003;
}

Is there a way to not duplicate the map?

My server block:

server {
    listen 443 ssl;
    ssl_certificate         /etc/ssl/nexello.crt;
    ssl_certificate_key     /etc/ssl/nexello.key;
    server_name             _;
    proxy_set_header Host             $host;
    proxy_set_header X-FORWARDED-FOR  $remote_addr;

    charset utf-8;

    location / {
        # Web based access
        # Cookies are used instead of a header because the request passes through here before any javascript can even set a Header.
        if ($cookie_token) {
            proxy_pass https://$version_host;
        }

        # API based access
        # Here we use headers because anyone that is using the API has full control of the headers.
        if ($http_authorization) {
            proxy_pass https://$version_api_host;
        }

        # Auth
        # In case there is no header or cookie we assume that it has no access token and should be redirected to the auth machine.
        proxy_pass https://172.17.0.1:7001;
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    I somewhat solved this as while there still is two maps, the options are stored in another file so there won't be any reptition:

    map $cookie_version $version_cookie_host {
        include /etc/nginx/versions.conf;
    }
    
    map $http_authorization $version_header_host {
        include /etc/nginx/versions.conf;
    }
    

    Contents of /etc/nginx/versions.conf:

    default 172.17.0.1:8001;
    2.65.1 172.17.0.1:8001;
    2.65.2 172.17.0.1:8003;
    

  2. You could use

    map $cookie_version$http_app_version $version_host {
        default 172.17.0.1:8001;
        # your complicated regex here since two variables will be concatenated.
    }
    

    and use $version_host in proxy_pass.

    Also offtopic, since you’re using if be careful with it
    https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search