Unexpected location regex behaviour

nginx mailing list
[email protected]

nginx mailing list
[email protected]

On Wed, Mar 09, 2016 at 11:31:08AM +0000, Peter Molnar wrote:

Hi there,

I’m facing some strange, unexpected regex behaviour in my setup.

I think the answer is at Module ngx_http_rewrite_module and the “last” flag.

What do you want to happen if the incoming request is for

What have you configured nginx to do if the incoming request is for

location @filesmagic {
rewrite “^/files/(.*?)-[0-9]{2,4}x[0-9]{2,4}.jpg$”
/wp-content/cache/$1-180x180.jpg last;

The goal of the first rule is to block access to original, unresized
files in a WordPress setup.

The first rule matches a lot more requests than just those ones.

This is what should happen:

  • full size image, should be blocked

That is, request should match the first location and be processed there.

“Processed” is “rewrite and start again”; or “do not rewrite and allow
or deny”. “Start again” will get it back to this location, but the
rewrite will not happen the second time around because the new request
not match the rewrite.


  • resized image, file exists, should be served

That is, request should match the second location, and one of the first
two try_files arguments should cause it to be served from the


  • resized image, file does not exist, smaller file should be served

That is, request should match the second location, and the final
argument should cause it to be handled in the third location.

But in that location, the rewrite will happen and the whole thing starts

Now the request is for
which matches the first location.

In the first location, the rewrite does not match and so the request is
allowed or denied.

As I see it, you could either add a location{} to match your
/wp-content/cache/ requests; or your @filesmagic rewrite could be to
/files/$1-180x180.jpg, so that it will not match the first location.

There probably are other ways too.

Good luck with it,


Francis D. [email protected]