Add slash to the end of every url (need rewrite rule for nginx)

Gomez picture Gomez · Mar 14, 2009 · Viewed 75.4k times · Source

I try to get an "/" to every urls end:

example.com/art

should

example.com/art/

I use nginx as webserver.

I need the rewrite rule for this..

For better understanding check this:

http://3much.schnickschnack.info/art/projekte

If u press on a small thumbnail under the big picture it reloads and shows this url:

http://3much.schnickschnack.info/art/projekte/#0

If i now have a slash on all urls (on the end) it would work without a reload of the site.

Right now i have this settings in nginx-http.conf:

server {
  listen *:80;
  server_name 3much.schnickschnack.info;
  access_log /data/plone/deamon/var/log/main-plone-access.log;
  rewrite ^/(.*)$ /VirtualHostBase/http/3much.schnickschnack.info:80/2much/VirtualHostRoot/$1 last;
  location / {
    proxy_pass http://cache;
  }
}

How do I configure nginx to add a slash? (I think i should a rewrite rule?)

Answer

Bob Monteverde picture Bob Monteverde · Oct 12, 2010

More likely I think you would want something like this:

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).