Nginx dynamic servername with regular expression doesn’t work for co.uk

httpnginxperlregexregular expressions

I'm trying to setup a nginx server which dynamically loads content from a folder for a domain. To do this I'm using regular expressions in the server name like so:

server_name ((?<subdomain>.+)\.)?(?<domain>.+)\.(?<tld>.*);

This will create a 3 variables for nginx to use later on, for example when using the following url: test.foo.example.com this will evaluate to:

  1. $subdomain = test.foo
  2. $domain = example
  3. $tld = com

The problem arises when the co.uk top-level domain is used. In this case when using the url test.foo.example.co.ukit will evaluate to:

  1. $subdomain = test.foo.cedira
  2. $domain = co
  3. $tld = uk

How can I edit the regular expression so that it will also work for co.uk?

Best Answer

This is able to check for the www part and also it gets just the first capture as the subdomain second capture as domain and the rest as the host-domain:

server_name ~^(www\.)?((?<subdomain>.+?)\.)?((?<domain>.+?)\.)?(?<host_domain>.+)\.(?<tld>co.uk)$ ~^(www\.)?((?<subdomain>.+?)\.)?((?<domain>.+?)\.)?(?<host_domain>.+)\.(?<tld>.*)$;