0

I'm trying to avoid duplicate content on my blog caused by trailing slashes. Currently, these URLs display the same content:

I found some custom code for the .htaccess file, but it's not working as expected, especially in incognito mode:

RewriteEngine on
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
RewriteEngine On
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+?)/$ /$1 [R=301,NE,L]
RewriteEngine On
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule ^ %1/%2 [R=301,L]

I want to ensure only one trailing slash. Any help is appreciated!

New contributor
DiegoB is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

1 Answer 1

0

To ensure that your URLs have a consistent trailing slash and avoid duplicate content, you can use the following .htaccess rules. These rules will enforce a single trailing slash for URLs and redirect any URLs without or with multiple trailing slashes to their correct form.

Here's the updated .htaccess code:

# Enable rewrite engine
RewriteEngine On

# Remove multiple trailing slashes
RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule ^ %1/%2 [R=301,L]

# Redirect URLs with trailing slash to without (only for URLs not ending with a file extension)
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+?)/$ /$1 [R=301,NE,L]

# Add trailing slash if not present (except for existing files and URLs with file extensions)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !\.[^./]+$
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.*)$ /$1/ [R=301,L]
2
  • Thank you, @mukto90, for the fast response. I included the code into the .htaccess file and, when testing it, I'm seeing an error saying ERR_TOO_MANY_REDIRECTS. If I remove the last part, the rest of the code works properly and removes the trailing slashes at the end. I'm not familiar with "Rewriterules," so I'll start reading about that to try to find out why that last piece is not working properly, but if you have any ideas, I'd really appreciate it.
    – DiegoB
    Commented 2 days ago
  • After looking a bit more inside the browser console I can see how the rules overlap with each other (share.zight.com/4gu8ZLbR) You can see in that image how the first time it loads it removes all the trailing slashes and then adds just one but when the page loads again the process starts from the scratch. It should be possible to add a condition to ignore the rules if the page only has one single trailing slash. I'll search for that too.
    – DiegoB
    Commented 2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.