Nginx – Friendly URL Rewrite Rules

centoshttpdmod-rewritenginxrewrite

I have recently migrated from Apache to Nginx and the performance is impeccable.
The site is a download server (mainly) with a custom PHP script.

Some example URLs are like:

https://sub.example.com
https://sub.example.com/index.php?dir=foo1/
https://sub.example.com/index.php?dir=foo2/
https://sub.example.com/index.php?dir=foo2/bar1/
https://sub.example.com/index.php?dir=foo2/bar2/

I would like to make them friendly-URLs so the above becomes:

https://sub.example.com
https://sub.example.com/foo1/
https://sub.example.com/foo2/
https://sub.example.com/foo2/bar1/
https://sub.example.com/foo2/bar2/

Please note the trailing slash our PHP script produces.
The directory is accessible with or without that slash (when manually typing URL) and needs to be accessible with or without that after the rewrite.

Any ideas on the rewrite conf for Nginx?

Best Answer

You could use try_files to make a difference for files which actually exist on your filesystem and URIs you like to give as parameter like yours /foo1/.

location = / {
  try_files $uri /index.php?dir=$uri;
}

In PHP this would produce:

echo $_GET['dir'];
# /foo1/