Using nginx args helper to search for a URL param

Using nginx args helper to quickly check for a param in a request

Recently I needed an efficient way to quickly shut down a network request if the request contained a parameter of ?search=blah. This was for one of our favourite clients.

The value of the parameter didn’t matter, if the parameter existed in the request, I wanted to return a 401 Unauthorised. This was to help with a spam problem.

The project uses an nginx proxy service, so I needed a way to check the request and return a 401 as soon as possible, I didn’t want to waste the proxy’s time and I certainly didn’t want to bother the server with anything.

Enter $arg_search

I had no idea nginx let’s you write if $arg_blah and if whatever is after the _ exists in the request the it will return true.

That means we can do something like the below, if ?search is in the request, we return a 403.

server {
  listen 8080;
  listen [::]:8080;

  server_name myawesomesite.com;

  # We want to forbid any traffic to /?search=blah
  if ($arg_search) {
    return 403;
  }
}

Here is the (one line) entry in nginx docs.

Recent posts View all

Web DevProductivity

Keeping on top of website updates

Learn what website updates are, what they entail, why they are important, and how we can help

Freelancing

Getting the most out of your agency

Here are some tips based on years of working with, for, and as an agency on how to get the most out of any work you do.