0
0
NginxHow-ToBeginner · 3 min read

How to Add Trailing Slash in Nginx: Simple Redirect Setup

To add a trailing slash in nginx, use a rewrite directive or a location block that checks if the URL lacks a trailing slash and then redirects to the same URL with a slash. This ensures consistent URL formatting and avoids duplicate content issues.
📐

Syntax

The main syntax to add a trailing slash uses the rewrite directive inside a server or location block. It checks if the requested URI does not end with a slash and then redirects to the URI with a slash appended.

Key parts:

  • rewrite: Nginx command to change the URL.
  • ^([^.]*[^/])$: Regular expression matching URIs without a trailing slash and not ending with a dot (to exclude files).
  • $1/: The captured URI with a slash added.
  • permanent: Sends a 301 redirect to the client.
nginx
rewrite ^([^.]*[^/])$ $1/ permanent;
💻

Example

This example shows a complete server block that redirects URLs without trailing slashes to ones with trailing slashes, except for requests to files (like .html or .jpg).

It demonstrates how to keep URLs consistent and improve SEO by avoiding duplicate content.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        # Redirect URLs without trailing slash to add slash
        rewrite ^([^.]*[^/])$ $1/ permanent;

        # Usual processing for requests with trailing slash
        try_files $uri $uri/ =404;
    }
}
Output
Request: http://example.com/about Response: 301 Moved Permanently to http://example.com/about/ Request: http://example.com/image.jpg Response: 200 OK (no redirect, serves the file)
⚠️

Common Pitfalls

Common mistakes when adding trailing slashes in Nginx include:

  • Redirect loops caused by incorrect rewrite rules.
  • Redirecting requests for files (like images or scripts) which should not have trailing slashes.
  • Using rewrite outside of proper location blocks causing unexpected behavior.

Always test redirects carefully to avoid infinite loops and exclude static files from trailing slash redirects.

nginx
## Wrong way (causes redirect loop):
rewrite ^(.*[^/])$ $1/ permanent;

## Right way (excludes files):
rewrite ^([^.]*[^/])$ $1/ permanent;
📊

Quick Reference

Summary tips for adding trailing slash in Nginx:

  • Use regex to match URLs without trailing slash but exclude files.
  • Use permanent flag for SEO-friendly 301 redirects.
  • Place rewrite rules inside location / or server block.
  • Test with different URLs to avoid redirect loops.

Key Takeaways

Use a rewrite rule with regex to add trailing slashes only to URLs without file extensions.
Place the rewrite directive inside the appropriate location or server block to avoid conflicts.
Use the permanent flag to send a 301 redirect for SEO benefits.
Test your configuration to prevent redirect loops and unintended redirects on files.
Consistent trailing slashes help avoid duplicate content and improve URL clarity.