Can't Reach Allowed File when My User Agent is Blocked

My nginx.conf file contains the following snippet:

  deny 192.168.1.1;
  if ($http_user_agent ~ "blockeduseragent") {return 403;}

  error_page 403 /403-error-handler.html;
  location = /403-error-handler.html {
     allow all;
     internal;
  }

  location = /message-to-users.html {
     allow all;
     #internal;
  }

When I am coming from 192.168.1.1, I can see the custom 403 error message (403-error-handler.html) and the message-to-users.html. However, when I am coming from an allowed IP address and my browser’s user agent is blockeduseragent, I cannot get to the custom 403 error message or the message-to-users.html.

I am using Nginx verison 1.22.1 on a server running Raspbian OS Bookworm.

I have no idea what to try next, because this makes zero sense to me.

2 Likes

From what I have gathered, I think because you’re using the return (link) directive which is more abrupt than say the deny(link) directive. I believe what is occurring is the following.

  • The return 403; directive immediately terminates the request
  • It bypasses nginx’s normal error page processing
  • The error_page directive is never triggered
  • No further location processing occurs

Try replacing the “return 403” directive with the “deny” directive. Does this generate the desired outcome you’re looking for?

if ($http_user_agent ~ "blockeduseragent") {deny all;}

Hey there!

In addition to what @Dylen said, I also want to note that NGINX 1.22.1 is now around 4 years old (we are at 1.28.0 these days) and that running NGINX on Raspbian is not officially supported at this point in time. I would at the very least try to update NGINX to the latest version :slightly_smiling_face:.

You should also be able to achieve your use case using map instead of if. The if directive in NGINX breaks the usual processing flow and can lead to some weird behaviours. In this case, since NGINX reads its config top to bottom, it is hitting the if statement and promptly exiting due to the return statement (like @Dylen mentioned) before your custom error page and message to users gets parsed and loaded. There seems to be a decent article here covering how to use map instead of if.

1 Like

Removing the “internal;” statement in the 403-error-handler.hml block seems to have fixed the problem.

1 Like

I can see how that might have fixed the 403 issue if you were using an external IP, but you should have been able to see the message-to-users site just fine. And I would still suggest using a map instead of if per my previous comments. There will be scenarios where your entire config won’t get properly processed if NGINX hits an if block at the wrong moment. Glad you could get your config working though!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.