sanjay
sanjay

Reputation: 1

Wordpress - Trailing Slash using .htaccess file

I am creating a plugin to add the trailing slash to all the URLs of the site using .htaccess file. When I am adding the code to forcefully add the trailing slash, all the pages are redirecting multiple times and throwing an error of ERR_TOO_MANY_REDIRECTS.

I know we can add trailing slash using permalinks in wordpress, but want to achieve it through the .htaccess file.

.htaccess file of Default wordpress is having below code.

# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

On the top of above code when I am trying to add below code of for adding trailing slash, I am getting the error of too many redirects.

# Force trailing slash
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_URI} !^/wp-json/
RewriteCond %{REQUEST_FILENAME} !\.(gif|jpg|png|jpeg|css|xml|txt|js|php|scss|webp|mp3|avi|wav|mp4|mov|pdf|html|htm|xst)$ [NC]
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301]

Error page is shown like below.

Error Image After adding the code for trailing slash

I stuck in this since last multiple days and still not able to find the proper solution. Can someone please help? Any help would be appreciated.

Thanks you in advance.

Upvotes: 0

Views: 379

Answers (1)

Rahat
Rahat

Reputation: 3

Check this.

RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]

This works for me, try this.

Upvotes: 0

Related Questions