Search code examples
apache.htaccessmod-rewriteserverwebserver

Redirect to index.php and remove trailing slash .htaccess


There appears to be many questions like this here but can't find an answer that fits my current code:

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^ public/index.php [QSA,L]

This redirects everything to public/index.php which works fine but I want to get rid of the trailing slash so that example.com/foo/ becomes example.com/foo


Solution

  • You can insert a trailing slash removal code before your current rule:

    RewriteEngine On
    
    ## Unless directory, remove trailing slash
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} ^(.+)/+$
    RewriteRule ^ %1 [R=301,NE,L]
    
    ## forward all requests to public/index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ public/index.php [L]