3

I already make extensive use of rewrite in nginx to perform this sort of thing:

/photos/123344               ->    /photos/photos.php?id=123344
/photos/london-2016          ->    /photos/photo-shoot.php?name=london-2016

Currently I have no rule for other (non-dynamic) pages. E.g

/photos/shoot-register.php   ->    /photos/shoot-register.php

Which I'd like to become

/photos/shoot-register.php   ->    /photos/shoot-register

But without specifying an individual rewrite rule for each .php file.

It seems that try_files is the correct directive here:

location ~ ^/photos {
    try_files $uri $uri.php?$args;
    rewrite ^/photos/([0-9]+)(/?)$        /photos/photo.php?id=$1;
    rewrite ^/photos/([^/\.]+)(/?)$       /photos/photo-shoot.php?name=$1;
}

But this doesn't work, unless I delete the two rewrite lines.

I assume that means that execution doesn't stop after try files? It finds "shoot-register.php" but then carries on executing and ends up with /photos/photo-shoot.php?name=shoot-register.php?

How can I make it stop after try_files succeeds in finding a match?

Thanks

Codemonkey
  • 4,455
  • 5
  • 44
  • 76

1 Answers1

4

what if you move the rewrites to separate named location, and then change your try_file directive to try the file, then the php file and then directing to the new location?

location ~ ^/photos {
    try_files $uri $uri.php?$args @rewrites;
}

location @rewrites {
    rewrite ^/photos/([0-9]+)(/?)$        /photos/photo.php?id=$1;
    rewrite ^/photos/([^/\.]+)(/?)$       /photos/photo-shoot.php?name=$1;
}
miah
  • 10,093
  • 3
  • 21
  • 32
  • Certainly a workable solution, is that the best practice, it seems unnecessarily compared to the untrained eye? – Codemonkey Oct 26 '16 at 16:45
  • It's the only one I can think of. The issue is that the try_files directive doesn't stop and return when one of the options is valid. In your version, it would stop at the .php part, and then continue through the location directive. In my version, it does the same thing, but since the rewrite directives aren't there, it returns the content you are expecting. – miah Oct 26 '16 at 20:09