如何对nginx配置文件中的变量进行简单的数学计算

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

无论如何我可以对ngnix配置文件进行简单的数学计算。可以说我想根据主机域进行代理传递。当前缀为 0 到 9 时,我能够将主机重定向到正确的端口号。但是我真正想要的是前缀 10 到端口 1410。但是根据我现在的配置,它将代理到端口 14010

主持人:
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;
    }
}

这可以使用 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 魔术和正则表达式轻松完成:

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;        # 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;
    }
}

thx,原来我只需要写 设置 $custom_port $变量; 如果 ($custom_port ~ "^.{3}$") { 设置 $custom_port 140$变量; }

另一种(我会说更干净)方法是在配置中使用 hardocoded/autogenerated 映射,如下所示:

map $prefix $custom_port {
  0    1400
  10   1410
  99   1499 
  # any other values/numbers 
}

server {
    server_name ~^(prefix(?<prefix>[0-9]+)).domain.com;
    location / {
        proxy_pass http://127.0.0.1:$custom_port;
    }
}