Sometimes NGINX may show trailing slash in website URLs. Here’s how to remove trailing slash in NGINX to make your URLs look more intuitive.
Remove trailing slash in NGINX
Here are the steps to remove trailing slash in NGINX.
1. Open NGINX configuration file
Open terminal and run the following command to open NGINX server configuration file.
$ sudo vi /etc/nginx/nginx.conf
If you have configured separate virtual hosts for your website (e.g www.example.com), such as /etc/nginx/sites-enabled/website.conf then open its configuration with the following command
$ sudo vi /etc/nginx/sites-enabled/website.conf
Bonus Read : How to Install & Configure ModSecurity in NGINX
2. Remove trailing slash
Add the following rewrite rule in server block as shown in bold. Replace example.com below with your domain name
rewrite ^/(.*)/$ /$1 permanent;
In the above code, the rewrite statement will redirect all URLs to those without trailing slash.
If you want to remove trailing slash from only a specific URL (e.g /product/) then update the rewrite statement as shown below.
rewrite ^/product/$ /product permanent;
Bonus Read : How to Enable NGINX Status Page
3. Restart NGINX Server
Run the following command to check syntax of your updated config file.
$ sudo nginx -t
If there are no errors, run the following command to restart NGINX server.
$ sudo service nginx reload #debian/ubuntu $ systemctl restart nginx #redhat/centos
Bonus Read : How to Install Varnish Cache in NGINX
Hopefully the above tutorial will help you remove trailing slash from URLs in NGINX. You can also use the above steps to remove other trailing characters such as hash (#) from URL.