How to Add Trailing Slash in NGINX

add trailing slash in nginx

Sometimes, you might need to add a trailing slash at the end of every URL of your website. NGINX allows you to easily do it in just one line. Let us take a look at how to add a trailing slash in NGINX.


How to Add Trailing Slash in NGINX

Here are the steps to add trailing slash in NGINX.


1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation



$ sudo vim /etc/nginx/nginx.conf


2. Add Trailing Slash to Every URL

Let’s say you want to add a trailing slash to all URLs on your website, but not for any files (.jpg, .png). In that case, add the following rewrite rule in location / block

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

The above regular expression will rewrite all URLs without any ‘.’ in them and that don’t end in a ‘/’. This is done to avoid your files such as CSS, JS from getting a trailing slash as well as prevent redirect loops in case of certain PHP frameworks that also rewrite on their own.

If you want to add trailing slash only to URLs in a directory (/product/), then add the above rewrite rule in the location block of that directory

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


If you also DON’T want query strings to get a trailing slash

location / {
  rewrite ^([^.\?]*[^/])$ $1/ permanent;




3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t


If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload


That’s it! Now NGINX will automatically add a trailing slash to all URLs except files that are served from your website.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!