nginx: Proxying none or one defined query string

I wanted to build a reverse proxy configuration for a web app. But on a certain URL, I wanted to allow either none or one specific query string.

Here is a snippet from my nginx configuration:

location /my/app {
    if ($query_string !~ "(^$)|(^key=value$)") {
        return 404;

    proxy_pass https://app.example.local/my/app;

The regex (^$)|(^key=value$) does the magic. If the URL doesn't match on the regex, nginx returns HTTP status 404. If it does match, nginx proxies the request to the web app.

Published on 2022-02-20, 15:13 +0000