7

I have as below in nginx but it doesn't do what I intend:

location / {
  if ($host !~* blah.blah.com) {
    return 307 https://$host/$request?uri;
  }
}

I basically need to do a 307 when $host doesn't match blah.blah.com in regex or it could really just be a plain string. I tried putting them in double quotes or /.../ but nothing seems to work. How do I specify this in nginx's location block?

1 Answer 1

11

As you say, you do not need to use a regular expression to match a single string. You can use the = and != operators with the if directive. See this document for details.

For example:

if ($host != foo.example.com) { ... }

The correct regular expression for the above requires two anchors (^ and $) and an escape for the . which would otherwise represent any character.

For example:

if ($host !~* ^foo\.example\.com$) { ... }

The use of quotes is optional, unless the string contains reserved characters (such as { and }).

See this link for more on regular expressions.

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

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.