skip to Main Content

I’m trying to set up an Nginx, where I want to add two numbers together.

server {
        server_name "~^pr-(d*).review-apps.example.com$";
        
        location / {
            set $port 50000+$1;
            proxy_pass "http://localhost:$port/test";
        }
    } 

But this doesn’t work 🙄. (Result is in string. For example "50000+125")

How can I add two numbers in nginx.conf? Is it even possible?

2

Answers


  1. No, it is not possible to use math with standard modules. There might be a chance with lua module but you probably shouldn’t as NGINX wasn’t meant to be used like that. It is like using a screwdriver to hammer a nail – it is possible that you succeed but it is also possible that you poke out an eye along the way.

    I suggest you reconsider the design of your application, perhaps there is a better/commonly used way to achieve what you want.

    Login or Signup to reply.
  2. If you use fixed length numbers, for example only three digits, for this particular case you can use string concatenation instead of adding numbers:

    server {
        server_name "~^pr-(d{3}).review-apps.example.com$";
            
        location / {
            set $port 50$1;
            proxy_pass "http://localhost:$port/test";
        }
    }
    

    This will give you exactly 50145 for the pr-125.review-apps.example.com hostname.

    For variable count of port number digits you can use named regex capture group:

    server {
        server_name  "~^pr-(?<pr1>d).review-apps.example.com$"
                     "~^pr-(?<pr2>d{2}).review-apps.example.com$"
                     "~^pr-(?<pr3>d{3}).review-apps.example.com$";
    
        location / {
            if ($pr1) { set $port 5000$pr1; }
            if ($pr2) { set $port 500$pr2; }
            if ($pr3) { set $port 50$pr3; }
            proxy_pass "http://localhost:$port/test";
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search