Nginx – How to serve first Nginx regex server_name servers

configurationnginxrouting

I have a Nginx config which look like this :

server {
  server_name sub2.sub1.example.com;
  listen 80;
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl;
  server_name sub2.sub1.example.com;

  ... 
}

server {
  listen 80;
  server_name ~^sub2\.sub1\.example\.com/toto/[abc]/.*$;

  ...
}

The Nginx documention says that Nginx evaluates server_names in the following order (http://nginx.org/en/docs/http/server_names.html) :

  1. exact name
  2. longest wildcard name starting with an asterisk, e.g. *.example.org”

  3. longest wildcard name ending with an asterisk, e.g. “mail.*”

  4. first matching regular expression (in order of appearance in a configuration file)

So, my server with the regex server_name will be evaluate last (in fact, will never be evaluated because the sub2.sub1.example.com match first)

Is there a way to prioritize the server which have a regex as server_name ?
Is the default_server directive do this ? It's not realy what the documentation seems to say.
Maybe I should use location instead of different server directives to resolve this problem ?

Jules

Best Answer

Ok I found a solution.

It's better to use some location directives for this problem.

So, now my config is :

server {
  listen 80 default_server;
  server_name sub2.sub1.example.com;

  ##### Non HTTPS conf #####
  location ~* ^/toto/[abc]/ {
    # This replace the "server_name ~^sub2\.sub1\.example\.com/toto/[abc]/.*$;" config block
    ...

  }

  ##### HTTPS conf #####
  location / {
    return 301 https://$host$request_uri;
  }
}

server {
  listen 443 ssl;
  server_name sub2.sub1.example.com;

  ...
}