Tips / Nginx

How to add a trailing slash to Nginx URLs

Yesterday I told you a tip about how to remove trailing slash from Nginx so today I’m gonna do the exact opposite, let’s see how to add a trailing slash to Nginx URLs.

In my last post I explained why we should remove trailing slash from nginx urls, and the same explanation is valid if you want to add a trailing slash, it’s all about Search Engine Optimization and avoid duplicate content that may hurt your google rankings.

Add a trailing slash by placing this inside your virtual host file in the server {} block configuration:

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

Full example:

server {
listen 80;
rewrite ^(.*[^/])$ $1/ permanent;

From now on, Nginx should add your trailing slash automatically to every url.

Popular search terms:

  • nginx trailing slash
  • nginx add trailing slash
  • nginx adding trailing /
  • nginx adding urls

Esteban Borges

Linux Geek, Webperf Addict, Nginx Fan. CTO @Infranetworking

  • Damien

    That is very useful.

    However that also will add a trailing slash to any file.css references and break the styling on the webpage

    How would you ensure it is not applied to any URLs with a .filetype on the end?


  • axl

    What about slashes after files extensions?

  • nachodev

    This should add the trailing slash only to directories (a path with no extension in the last part):

    rewrite ^([^?#]*/)([^?#./]+)([?#].*)?$ $1$2/$3 permanent;

    The first group will match everything until the last slash, the second group will match the last part of the path only if it has no dots in the name, and the last group will match the remaining of the URL (parameters and hash).

    • Robin

      This is excellent, and exactly what I needed. Thanks!