Search code examples
nginxreverse-proxy

how to do simple math calculation for variable in nginx configuration file


Is there anyway I can do simple math calculation for ngnix configuration file. Lets say I want to do proxy pass based on host domain. I am able to redirect host to correct port number when prefix comes with 0 to 9. However what I really want is prefix10 to port 1410. but based on my configuration right now, it will proxy to port 14010

Host:
http://prefix0.domain.com -> 127.0.0.1:1400
http://prefix10.domain.com -> 127.0.0.1:1410
http://prefix99.domain.com -> 127.0.0.1:1499

server {
    listen       80;
    server_name ~^(prefix(?<variable>[0-9]+)).domain.com;

    location  / {
        proxy_pass http://127.0.0.1:140$variable;
    }
}

Solution

  • This can be done easily with the ngx-perl or ngx-lua modules. But if you don't have them installed or are just looking for an old-school solution, there is a way to solve the problem with the good old rewrite magic and regular expressions:

    server {
        listen       80;
        server_name ~^(prefix(?<variable>[0-9]+)).domain.com;
    
        location  / {
            # Since it's always wise to validate the input, let's
            # make sure there's no more than two digits in the variable.
            if ($variable ~ ".{3}") { return 400; }
    
            # Initialize the port variable with the value.
            set $custom_port 14$variable;
    
            # Now, depending on the $variable, $custom_port can contain 
            # values like 1455, which is correct, or like 149, which is not.
    
            # Nginx does not have any functions like "replace" that could be 
            # used on random variables. However, the rewrite directive can
            # replace strings using regular expression patterns. The only 
            # problem is that the rewrite only works with one specific variable,
            # namely, $uri.
    
            # So the trick is to assign the $uri with the string we want to change,
            # make necessary replacements and then restore the original value or 
            # the $uri:
    
            if ($custom_port ~ "^.{3}$") {  # If there are only 3 digits in the port
                set $original_uri $uri;     # Save the current value of $uri
                rewrite ^ $custom_port;     # Assing the $uri with the wrong port
                rewrite 14(.) 140$1;        # Put an extra 0 in the middle of $uri
                set $custom_port $uri;      # Assign the port with the correct value
                rewrite ^ $original_uri;    # And restore the $uri variable
            }
    
            proxy_pass http://127.0.0.1:$custom_port;
        }
    }