Rewrite before regex location

Francis Daly francis at
Wed May 4 23:15:34 UTC 2016

On Thu, May 05, 2016 at 04:22:11AM +0530, Joyce Babu wrote:

Hi there,

> > Possibly using "location ^~ /test/" would work?

> There are over 300 rewrites under 54 location blocks.

If you've got a messy config with no common patterns, you've got a messy
config with no common patterns, and there's not much you can do about it.

If you can find common patterns, maybe you can make the config more
maintainable (read: no top-level regex locations); but you don't want
to break previously-working urls.

> I tried using ^~ as you suggested. Now the rewrite is working correctly,
> but the files are not executed. The request is returning the actual PHP
> source file, not the HTML generated by executing the script.

Can you show one configuration that leads to the php content being

If you rewrite /test/x.php to /test.php, /test.php should be handled in
the "~ php" location.

An alternative possibility could be to put these rewrites at server
level rather than inside location blocks. That is unlikely to be great
for efficiency; but only you can judge whether it could be adequate.

> > > location ~ [^/]\.php(/|$) {
> > >     fastcgi_split_path_info ^(.+?\.php)(/.*)$;
> > >
> > >     set $fastcgi_script_name_custom $fastcgi_script_name;
> > >     if (!-f $document_root$fastcgi_script_name) {
> > >         set $fastcgi_script_name_custom "/cms/index.php";
> > >     }
> >
> > I suspect that it should be possible to do what you want to do there,
> > with a "try_files". But I do not know the details.
> There is a CMS engine which will intercept all unmatched requests and check
> the database to see if there is an article with that URI. Some times it has
> to match existing directories without index.php. If I use try_files, it
> will either lead to a 403 error (if no index is specified), or would
> internally redirect the request to the index file (if it is specified),
> leading to 404 error. The if condition correctly handles all the
> non-existing files.

There is more than one possible try_files configuration; but that does not
matter: if you have a system that works for you, you can keep using it.

Good luck with it,

Francis Daly        francis at

More information about the nginx mailing list