Redirection to Enforce/Remove Trailing Slash on URLs

In this Article

Note: As long as your canonical URLs are correctly set, Google will index the desired URL even without these fixes.

Add a trailing slash

If you need to enforce a trailing slash at the end of your URLs you can use the following  helper plugin

📥  Download (.zip): WP Rocket | Enforce Trailing Slash on URLs
Developers: You can find the code for this plugin on GitHub.

These are the rules that the above helper plugin adds to the .htaccess file:

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

Remove a trailing slash

If you need to remove a trailing slash from the end of your URLs you can use the following  helper plugin. 

📥  Download (.zip): WP Rocket | Remove Trailing Slash from URLs
Developers: You can find the code for this plugin on GitHub

These are the rules that the above helper plugin adds to the .htaccess file:

# Remove trailing slash
RewriteCond %{REQUEST_URI} !wp-admin
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_METHOD} GET
RewriteCond %{REQUEST_URI} (.*)/$
RewriteCond %{REQUEST_FILENAME}
!\.(gif|jpg|png|jpeg|css|xml|txt|js|php|scss|webp|mp3|avi|wav|mp4|mov|pdf)$ [NC]
RewriteRule ^(.*)/$ /$1 [R=301,L]' . PHP_EOL . PHP_EOL;<br>

Trailing slashes on NGINX servers

Configuring NGINX is more complicated since WP Rocket does not have access to the configuration of a NGINX server; NGINX servers don't use .htaccess files, so, this type of server must be configured by a Sysadmin.

If you have access to the NGINX server configuration, you can use the next rules:

Force Trailing Slash:

# Force Trailing Slash (less REST API calls and files)

if ($request_uri !~ "^/wp-json") {
        rewrite ^([^.]*[^/])$ $1/ permanent;
}

Remove Trailing Slash:

# Remove Trailing Slash (less REST API calls and files)

if ($request_uri !~ "^/wp-json") {
        rewrite ^/(.*)/$ /$1 permanent;
}
Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.