将 NGINX var 从大写转换为小写

将 NGINX var 从大写转换为小写

我需要一些有关 nginx 配置设置的帮助。我的配置基本上是这样的...

map $http_apikey $api_client_name {
    default "";

    "CLIENT_ID" "client_one";
}

server {
  access_log /dev/stdout main;

  listen 443 ssl;
  server_name localhost;

  # TLS config
  ssl_certificate      /etc/nginx/ssl/cert.pem;
  ssl_certificate_key  /etc/nginx/ssl/key.pem;
  ssl_session_cache    shared:SSL:10m;
  ssl_session_timeout  5m;
  ssl_ciphers          HIGH:!aNULL:!MD5;
  ssl_protocols        TLSv1.2 TLSv1.3;

  proxy_intercept_errors on;     # Do not send backend errors to the client
  default_type application/json; # If no content-type then assume JSON

  location ~ ^/index-$http_apikey {
      if ($http_apikey = "") {
          return 401; # Unauthorized
      }

      if ($api_client_name = "") {
          return 403; # Forbidden
      }

      proxy_pass http://elasticsearch:9200;
  }

....

这个想法是从 POST 的标头信息中获取http_apikey并将其用作链接的一部分。但是 VAR,,http_apikey里面有大写字母以及小写字母和数字。但是 URI 应该全部小写,因此本质上:

  location ~ ^/index-$http_apikey.lower() {
      if ($http_apikey = "") {
          return 401; # Unauthorized
      }

      if ($api_client_name = "") {
          return 403; # Forbidden
      }

      proxy_pass http://elasticsearch:9200;
  }

location ~ ^/index-$http_apikey.lower()

有没有办法在 nginx 中做到这一点?就像在 bash 中一样,我只想${http_apikey,,}... 有 nginx 等效的吗?

谢谢

答案1

简短版本:不,那是不可能的。

简短但乐观的版本:仅使用 nginx 时这是不可能的,但使用 lua 扩展时是可能的。或者任何其他编程语言的 nginx 扩展,例如perl

长版本:所以你正试图在 nginx 配置文件中编写代码。尽管 nginx 配置确实提供了一些编程工具(设置变量、使用条件分支),但它的配置语言不是代码(编程语言和配置之间的主要区别在于代码语句按其出现的顺序处理,而配置语句的效果与其位置无关 - 这就是为什么 nginx 条件分支周围有很多噪音的原因(如果是邪恶的,以及类似的。)这可能是 Igor Sysoev 及其团队很久以前就意识到的事情,并开始实现 nginx 成熟的编程扩展 - lua,而不是修复 nginx 配置编程胚胎中的问题(这就是为什么它是部分和不完整的 - ifs 没有给出else,ifs 和 s 的顺序set是隐式的等等。因此,只要您想将代码放入 nginx 配置文件中,就应该开始使用 lua(或其他东西)。可以使用添加 Luaopenrestynginx 版本,其中包含正确构建的 lua 以及大量扩展和示例,或者仅仅单独添加 thd lua nginx 模块,这取决于您使用的发行版。

相关内容