Don't process requests containing folders

Grant emailgrant at
Mon Sep 12 20:55:35 UTC 2016

>> My site doesn't have any folders in its URL structure so I'd like to
>> have nginx process any request which includes a folder (cheap 404)
>> instead of sending the request to my backend (expensive 404).
>> Currently I'm using a series of location blocks to check for a valid
>> request.  Here's the last one before nginx internal takes over:
>> location ~ (^/|.html)$ {
>> }
> I think that says "is exactly /, or ends in html".

Yes that is my intention.

> I'm actually not sure whether this is intended to be the "good"
> request, or the "bad" request. If it is the "bad" one, then "return
> 404;" can easily be copied in to each. If it is the "good" one, with a
> complicated config, then you may need to have many duplicate lines in
> the two locations; or just "include" a file with the good" configuration.

That's the good request.  I do need it in multiple locations but an
include is working well for that.

>> Can I expand that to only match requests with a single / or ending in
>> .html like this:
>> location ~ (^[^/]+/?[^/]+$|.html$) {
> Since every real request starts with a /, I think that that pattern
> effectively says "ends in html", which matches fewer requests than the
> earlier one.

That is not what I intended.

> If you want to match "requests with a second slash", do just that:
>   location ~ ^/.*/ {}
> (the "^" is not necessary there, but I guess-without-testing that
> it helps.)

When you say it helps, you mean for performance?

> If you want to match "requests without a second slash", you could do
>   location ~ ^/[^/]*$ {}
> but I suspect you'll be better off with the positive match, plus a
> "location /" for "all the rest".

I want to keep my location blocks to a minimum so I think I should use
the following as my last location block which will send all remaining
good requests to my backend:

location ~ (^/[^/]*|.html)$ {}

And let everything else match the following, most of which will 404 (cheaply):

location / { internal; }

- Grant

More information about the nginx mailing list