Last updated on September 13, 2023

Add a Trailing Slash To the URL

Don’t know where to add this snippet? Read our guide: How to add code snippets.

Add a trailing slash to the URL.

If you want to add a trailing slash to the URL in WordPress, this can be done using the redirect_canonical filter. Here’s an example code snippet to add a trailing slash to URLs:

function wpsnippets_add_trailing_slash( $redirect_url ) {
    
    return trailingslashit( $redirect_url );
}

add_filter( 'redirect_canonical', 'wpsnippets_add_trailing_slash' );

In this code snippet, we define a function wpsnippets_add_trailing_slash() that takes the original redirect URL as a parameter and add a trailing slash using the trailingslashit() function. We then return the modified URL to the redirect_canonical filter.

By adding this code snippet to your WordPress site, URLs without a trailing slash will be redirected to the same URL with a trailing slash, which can be useful for SEO purposes and for ensuring that URLs are consistent throughout your site.

Note that if your WordPress site is using a caching plugin, you may need to clear the cache after adding this code snippet to ensure that the redirects are applied correctly.

Alternative method: Modifying the .htaccess file

Instead of using the above code snippet, you can also add a trailing slash to URLs by modifying the .htaccess file, following these steps:

  1. Access your WordPress website’s root directory via FTP or File Manager in cPanel.
  2. Find the .htaccess file and download it to your computer as a backup.
  3. Open the .htaccess file in a text editor.
  4. Add the following code at the beginning of the file:
RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_URI} !(.*)/$ 
RewriteRule ^(.*)([^/])$ $1$2/ [L,R=301] 
  1. Save the changes and upload the modified .htaccess file back to your website’s root directory.
Last updated on September 13, 2023. Originally posted on May 12, 2023.

Leave a Reply