Score:0

nginx: How to match server with shorter regex first when both have the same TLD?

sc flag

I'm trying to configure nginx to support two server name schemes.

Current: https://custid.hosted-environment.com/test/app-name/ Proposed: https://app-name.test.custid.hosted-environment.com

The current scheme works just fine, but trying to support both the current and proposed scheme and have nginx direct to the correct server based on the host does not seem to be working.

Here is an abbreviated version of the config I'm using, I've tried to trim it down to just the parts that are relevent:

http {
  server {
    listen       443        ssl http2;
    listen       [::]:443   ssl http2;

    server_name  ~^(?<app_custid>[^.]+)(?<app_domain>.hosted-environment.com)$;

    root /opt/nginx/apps/;

    location ~ ^/(?<app_env>dev|test|prod)/(?<app_name>app-name)/server(?<request_path>.*) {
      include /opt/nginx/config/nginx/proxy.conf;
      proxy_pass  https://backend_server;
    }

    location ~ ^/(?<app_env>dev|test|prod)/(?<app_name>app-name)(?<request_path>.*) {
      ssi on;
      ssi_types *;

      root /opt/nginx/;

      try_files
                /apps/$app_env/$app_name/dist/client/$request_path
                /apps/$app_env/$app_name/dist/client/index.html
                =404;
    }
  }

  server {
    listen       443        ssl http2;
    listen       [::]:443   ssl http2;

    server_name  ~^(?<app_name>[^.]+)\.(?<app_env>dev|test|prod)\.(?<app_custid>[^.]+)(?<app_domain>.hosted-environment.com)$;

    root /opt/nginx/;

    location ~ ^/server(?<request_path>.*) {
      include /opt/nginx/config/nginx/proxy.conf;
      proxy_pass  https://backend_server;
    }

    location ~ ^/(?<request_path>.*) {
      root /opt/nginx/;

      try_files
                /apps/$origin_env/$origin_app_name/dist/client/$request_path
                /apps/$origin_env/$origin_app_name/dist/client/index.html
                =404;
    }
  }
}

With this config, whichever server block I put first is the one that will handle the request. How can I make nginx use the correct server block based on the host?

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.