0

I've got an nginx instance on the Internet that proxies an application. I would like to return 404 on any request from the Internet that attempts to authenticate to the application, as all of the public parts of it allow anonymous access. Only users on the local network should be able to authenticate to it.

I imagine I can use a simple if block, as I'm just using return 404, but I am unsure what the most reliable if condition to detect the presence of authentication headers:

if (auth headers exist) {
  return 404;
}

Does anyone have suggestions on what I can put in the if block to check for this?

2 Answers 2

0

In general, if statements are not recommended, or you should at least be aware of some of the side-effects. Read "If is Evil" on nginx blog to learn more.

To answer your question: assuming the Header you're wanting to check, is called "Authorization", your initial assumption was very accurate already.

if ($authorization) {
    return 404;
}

That should do the trick already. Additionally if you wanted to only enforce this for the public server-block, you could use the ngx_http_access_module

1
  • If is problematic inside location, as described in the linked article; that does not mean it is not recommended in general. Commented Dec 23, 2022 at 9:17
0

You can check for the presence of the Authorization header in the request, which is usually used to authenticate requests. You can do this by using the $http_authorization variable in the if block:

if ($http_authorization) {
  return 404;
}

Alternatively, you can check for the presence of specific authentication headers that your application uses. For example, if your application uses X-Auth-Token as an authentication header, you can check for it like this:

if ($http_x_auth_token) {
  return 404;
}

Remember that the if block will only be evaluated if the request is made to a location protected by the auth_basic directive. If you want to check for the presence of authentication headers in all requests, you can use the map directive instead:

map $http_authorization $block_public_auth {
  default 0;
  "~" 1;
}

server {
  ...

  location / {
    if ($block_public_auth) {
      return 404;
    }

    ...
  }
}

Above will block all requests with an Authorization header, regardless of the location, it is made to.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .