How do I remove trailing slash in redirected URLs?

100 views Asked by At

I use this redirect for specific URLs to remove the .php extension and it works, but adds trailing slash at the end of each redirected URL. How do I remove that trailing slash only from the redirected URLs in this rule:

RewriteEngine On
RewriteBase /

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(about|contact)(\.php)?$ /$1/ [R=302,L]
RewriteRule ^(about|contact)/$ $1.php [END,QSA,NC]

I tried adding this rule RewriteRule (.*)/$ $1 [R=301,L] additionally, but I get an error on those same pages.

1

There are 1 answers

2
MrWhite On
RewriteRule ^(about|contact)(\.php)?$ /$1/ [R=302,L]
-----------------------------------------^

Because you are appending a trailing slash here ^

RewriteRule ^(about|contact)/$ $1.php [END,QSA,NC]
----------------------------^

However, you are also expecting a trailing slash in the following rule (above). So you can't simply remove the trailing slash in the first rule without also modifying the second rule.

These rules are focused on enforcing a trailing slash. To avoid the trailing slash you need to change both rules (not add another rule) to the following:

RewriteEngine On

RewriteRule ^(about|contact)\.php$ /$1 [R=302,L]
RewriteRule ^(about|contact)$ $1.php [END]

If you are using the END flag on the 2nd (rewrite) rule then the RewriteCond directive on the first rule that checked the REDIRECT_STATUS env var is not required.

Since you are no longer appending a trailing slash, the .php extension on the first rule should not be optional (as you had it originally). Otherwise, you will get a redirect-loop.

You should avoid the NC flag on the second rule as this promotes duplicate content (but you aren't using this on the first rule anyway). The QSA flag on this rule is not required.

You don't need the RewriteBase directive here and should be omitted.

To clarify, you should be linking to /about and /contact (no .php extension) in your internal links.