1

I have a development server setup that does some dynamic rooting to allow me to set up quick test projects by detecting domain and subdomain in server_name and using it to set the root.

server_name ~^(?<subdomain>\w*?)?\.?(?<domain>\w+\.\w+)$;

This works well, allowing me to set the root path based on variables $subdomain and $domain

For a specific type of project though, I also need to be able to further split the subdomain variable into two variables base on if the subdomain contains a dash.

e.g.

mysubdomain should not split but remain as variable $subdomain,

but mysubdomain-tn would be seperated into 2 variable $subdomain and $version

1 Answer 1

5

You need to complicate your regular expression a bit more:

server_name ~^(?<subdomain>\w*?)(-(?<version>\w*?)?)?\.?(?<domain>\w+\.\w+)$;

EDIT:

There are several ways to debug an Nginx configuration, including the debugging log, echo module and, in some extreme situations, even using a real debugger. However, in most cases adding custom headers to the response is enough to get the necessary information.

For example, I tested the regular expression above using this simple configuration:

server {
    listen 80;

    server_name ~^(?<subdomain>\w*?)(-(?<version>\w*?)?)?\.?(?<domain>\w+\.\w+)$;

    # Without this line your browser will try to download
    # the response as if it were a file
    add_header Content-Type text/plain;

    # You can name your headers however you like
    add_header X-subdomain "$subdomain";
    add_header X-domain "$domain";
    add_header X-version "$version";

    return 200;
}

Then I added domains mydomain.local, mysubdomain-tn.mydomain.local and mysubdomain-tn.mydomain.local to my hosts file, opened them in a browser with open debug panel (F12 in most browsers) and got the results.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I got close but I couldn't work out how to make the regex work with and without the dash. Not being able to easily inspect variables in ngix config makes it hard to debug. Any tips?
@Finglish, I added some additional explanations to the original answer.
Really Helpful! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.