Tag 84/2016: How to deny requests by filename, extension and patterns with nginx in a comfortably bureaucratic manner

In a current setup where nginx acts as a reverse proxy to some Apaches I want to deny access to some useless Flotsam & Jetsam files.

What I not want is to craft wonderful regular expressions that suffice type 3 of a Chomsky-Hierarchy while learning about Pumping-Lemmata, albeit that sounds very alluring for an annoyingly hot summerday later this year (Todo).

So in order to keep my various location directives specific as they are I create a map like this (example):

map $uri $reqhide {
 default 0;
 "~*robots.txt$" 0;
 "~*\.(md|txt)$" 1;
 "~*liesmich\.html$" 1;
}

This map has to be created in the http context of a config file and can then be used in if-conditions within location blocks. It uses the special parameter default to set the variable $reqhide in case of any non-matching pattern. If I want to hide files later on like all .txt files I set $reqhide to 1. A request for „robots.txt“ is caught by the first matching regular expression, so a request for „foo.txt“ is caught by the second that goes for all .txt files. The complete order of priority is explained in the map-module-docs.

As this wonderfully unknown (to many) article on nginx.com notes, the only 100% safe things in if conditions are return and rewrite statements.

So I just do something like

location / {
  [...]
  if ($reqhide) {
    return 404;
  }
  [...]
}

to make the response a 404-File-not-found lie.

Ein Gedanke zu „Tag 84/2016: How to deny requests by filename, extension and patterns with nginx in a comfortably bureaucratic manner“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.