Skip to content

Instantly share code, notes, and snippets.

@vburlak
Forked from esfand/nginxrewrite2.md
Created March 31, 2022 18:31
Show Gist options
  • Save vburlak/a9b7f07514f99c48758d0c578ec0a02b to your computer and use it in GitHub Desktop.
Save vburlak/a9b7f07514f99c48758d0c578ec0a02b to your computer and use it in GitHub Desktop.
Nginx Rewrite

Adding trailing slash to folders only

rewrite ^([^.]*[^/])$ $1/ permanent;

The Regular Expression translates to: "rewrite all URIs without any '.' in them that don't end with a '/' to the URI + '/'" Or simply: "If the URI doesn't have a period and does not end with a slash, add a slash to the end"

The reason for only rewriting URI's without dots in them makes it so any file with a file extension doesn't get rewritten. For example your images, css, javascript, etc and prevent possible redirect loops if using some php framework that does its own rewrites also

Another common rewrite to accompany this would be:

rewrite ^([^.]*)$ /index.php;

This very simply rewrites all URI's that don't have periods in them to your index.php (or whatever file you would execute your controller from).

Adding A Trailing Slash

By ThanhJanuary 04, 2011Technology

Some may ask what’s the point (it works as is with or without)? Well, when it comes to Search Engine Optimization, having duplicate may hurt your rankings. Therefore, it’s good practice to have a permanent (301) redirect for one or the other. For me, I prefer adding a trailing slash. And you simply do this by adding a nginx rewrite to your vhost:

# Adds a trailing slash to any urls that is missing a trailing slash
rewrite ^(.*[^/])$ $1/ permanent;

And if you prefer vice versa (urls without trailing slashes), just use the following rewrite instead:

# Remove trailing slash
rewrite ^/(.*)/$ /$1 permanent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment