0

How do I deny illegal host headers besides all subdomains (wildcard solution) and the main domain with nginx? When using this code below all of the subdomains stop working.

if ($host !~* ^(domain.com|*.domain.com)$ ) {
    return 444;
}

My server name is:

server_name domain.com *.domain.com;

How can this be accomplished?

1
  • ^ means "start of string". ^domain.com will NOT match foo.domain.com, because domain.com isn't at the start of the string. |*. will also not work. * is "zero or more of the previous", but you have no previous | is not a matching character, it's the regex equivalent of "or". Commented Aug 23, 2016 at 21:03

2 Answers 2

1

See if this works for you:

if ($host !~* ^(.+\.)?domain\.com$ ) {
    return 444;
}

You need to escape the periods, otherwise they will be interpreted as "any character". You can also simplify the regex a bit by matching an optional subdomain prefix before "domain.com".

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

Comments

1

A cleaner solution would be to create a separate (default) server block for "other" server names:

server {
    server_name .domain.com; # shorter form for "domain.com *.domain.com"

    ... # your main config here
}

server {
    listen *:80 default_server;
    server_name "";

    return 444;
}

Comments

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.