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


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


I use nginx as webserver.

I need the rewrite rule for this..

For better understanding check this:

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

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;
  access_log /data/plone/deamon/var/log/main-plone-access.log;
  rewrite ^/(.*)$ /VirtualHostBase/http/$1 last;
  location / {
    proxy_pass http://cache;

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

Best Answer

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

Related Topic