How to Remove Trailing Slash in Nginx Configuration
To remove a trailing slash in
nginx, use a rewrite directive inside your server block that matches URLs ending with a slash and redirects them to the same URL without the slash. For example, rewrite ^/(.+)/$ /$1 permanent; removes trailing slashes with a permanent redirect.Syntax
The rewrite directive in Nginx changes the requested URL based on a pattern. The syntax is:
rewrite regex replacement [flag];
Where:
regexmatches the URL pattern.replacementis the new URL to redirect to.flagcontrols the redirect type, e.g.,permanentfor HTTP 301.
nginx
rewrite ^/(.+)/$ /$1 permanent;Example
This example shows how to remove trailing slashes from all URLs except the root /. It redirects URLs ending with a slash to the same URL without it using a permanent redirect (HTTP 301).
nginx
server {
listen 80;
server_name example.com;
location / {
# Remove trailing slash except for root
rewrite ^/(.+)/$ /$1 permanent;
# Usual processing here
try_files $uri $uri/ =404;
}
}Output
When accessing http://example.com/path/, the browser is redirected to http://example.com/path with HTTP status 301 Moved Permanently.
Common Pitfalls
Common mistakes when removing trailing slashes in Nginx include:
- Using a rewrite rule that also removes the slash from the root URL
/, causing redirect loops. - Not specifying
permanentorredirectflags, which can cause unexpected behavior. - Placing the rewrite outside the correct
locationblock or server block.
Correct usage avoids redirect loops and ensures only URLs with trailing slashes (except root) are redirected.
nginx
server {
listen 80;
server_name example.com;
location / {
# Wrong: This causes redirect loop for root URL
rewrite ^/(.*)/$ /$1 permanent;
try_files $uri $uri/ =404;
}
}
# Corrected version:
server {
listen 80;
server_name example.com;
location / {
# Avoid root slash redirect by requiring at least one character before slash
rewrite ^/(.+)/$ /$1 permanent;
try_files $uri $uri/ =404;
}
}Quick Reference
Tips for removing trailing slashes in Nginx:
- Use
rewrite ^/(.+)/$ /$1 permanent;to avoid redirecting root URL. - Place rewrite inside the
location /block or server block. - Use
permanentflag for SEO-friendly 301 redirects. - Test redirects with curl or browser to confirm behavior.
Key Takeaways
Use the rewrite directive with regex ^/(.+)/$ to remove trailing slashes except for root URL.
Always include the permanent flag to send HTTP 301 redirects for SEO benefits.
Avoid redirect loops by not matching the root URL when removing trailing slashes.
Place rewrite rules inside the appropriate server or location block for correct behavior.
Test your configuration after changes to ensure URLs redirect as expected.