Handling trailing slash characters with Nginx 301 redirects

As a quick Nginx configuration example, if you need to configure a 301 Redirect with Nginx, and you also need to account for trailing slash characters in the original URL, I can confirm that this solution works for me:

rewrite /foo/bar/baz/?$  /foo/bar/baz.html permanent;

This Nginx configuration line will forward both of these URIs to the new URI:

/foo/bar/baz     # no trailing slash
/foo/bar/baz/    # with trailing slash

This works because the ? character means “zero or more instances of the preceding character,” and in this case the character before the ? is the / character.

I don’t know if this is important for a lot of systems, but I just converted a couple of old Drupal websites to use plain, static HTML files, and I needed to make sure I handled the redirect for some URLs that may or may not have had trailing slash characters.