Remove Trailing Slash in NGINX

John Doe ·

1337 Views

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

2. Remove trailing slash

Add the following rewrite rule in server block as shown in bold. Replace example.com below with your domain name

server { 
       listen 80; 
       server_name example.com; 
       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.

server { 
       listen 80; 
       server_name mydomain.com; 
       rewrite ^/product/$ /product permanent; 
}

 

* You can also use this method. Remove the trailing slash from all paths except mypath.

location ~ ^/mypath(.*) {
       try_files $uri @tomcat;
}
		
location ~ (?<no_slash>.*)/$ { 
       return 301 $no_slash;
}

...

location / {
       try_files $uri @tomcat;
}

location @tomcat {
...
}

 

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

 

nginx