Search code examples
apache.htaccessmod-rewritetrailing-slash

Remove trailing slash if not a directory with apache


I have the following rewrite rules:

#remove the www.
RewriteCond %{HTTP_HOST} ^www.website.co.uk$ [NC]
RewriteRule ^(.*)$ http://local.website.co.uk/$1 [R=301,L]

#this removes php extention
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L] 

# stops you accessing url with.php
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^.?\ ]+)\.php
RewriteRule ^([^.]+)\.php(/.+)?$ /$1%{PATH_INFO} [R=301]

I want to add in a rule that removes the trailing slash if someone tries to access site with one.

eg

website.co.uk/cheese/ should redirect to /cheese

as you can see I have a rule that redirects ursl with the .php extention, not sure where to begin.

I do have directory in the root folder which I do not wish to remove the trailing url, but I can add a ignore rule for those.

Cheers


Solution

  • Make the change below to your .htaccess file

    RewriteEngine on
    RewriteBase /
    
    #existing rule
    #remove the www.
    RewriteCond %{HTTP_HOST} ^www.website.co.uk$ [NC]
    RewriteRule ^(.*)$ http://local.website.co.uk/$1 [R=301,L]
    
    #new Rule
    #if its not a directory
    RewriteCond %{REQUEST_FILENAME} !-d
    #and it has a trailing slash then redirect to URL without slash
    RewriteRule ^(.+)/$ /$1 [L,R=301]
    
    # rest of your existing rules go here