Search code examples
phpwordpress.htaccesshttp-redirecttrailing-slash

WP rocket prevent 301 redirect to URL with trailing slash


When user access to my website with url:

example.com/post-name

Wordpress should perform 301 redirect to:

example.com/post-name/

But it's not working due the WP Rocket caching plugin (I couldn't find out why this is happening, but WP rocket is definitely causing problem)

Is it okay to perform wp_redirect to url with trailing slash? Is there any other solution except .htaccess redirect?


Solution

  • To prevent any intervention from WordPress and/or plugins, you could try forcing trailing slashes through .htaccess (Apache):

    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !/wp-json/ [NC]
    RewriteCond %{REQUEST_URI} !/wp-admin/ [NC]
    RewriteCond %{REQUEST_URI} !(/$|\.) 
    RewriteRule (.*[^\/])$ %{REQUEST_URI}/ [R=301,L] 
    </IfModule>
    

    The RewriteRule matches any path without a trailing slash through mod_rewrite (if enabled) and redirects to that same path with a trailing slash.

    The RewriteCond excludes paths in the /wp-json/ and wp-admin/ folder, as well as paths with dots, indicating files with an extension (e.g. .jpg, .css etc).

    Forcing a trailing slash in the /wp-json/ and wp-admin/ folders can cause problems in the WordPress admin panel and with Full Site Editing.