Apache Redirect and Rewrite

Viewed 42

In my .htaccess file I know how to rewrite a friendly URL:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+?)$ /index.php?index=$1 [L,QSA]

So, www.example.com/doit → www.example.com/index.php?doit where index.php will handle the rest.

However, I want to handle trailing slashes as well. I can use:

RewriteRule ^(.+?)/?$ /index.php?index=$1 [L,QSA]

which does work, but the URL keeps the trailing slash. I also suspect that the page thinks it’s in the wrong directory.

What I would like to do is catch the trailing slash first and redirect it to a non-slashed version:

www.example.com/doit/ → www.example.com/doit → www.example.com/index.php?doit

Presumably then the URL will be fixed, and the rewrite will act as normal.

Is that possible?

1 Answers

It's possible adding a RewriteCond, maybe there is a shortest way, but i've tested and it's working.

I hope I have answered your question and helped you

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_URI} ^(.*)\/$
RewriteRule ^(.+?)/$ /index.php?index=$1 [L,QSA]

RewriteRule ^(.+?)$ /index.php?index=$1 [L,QSA]

Testing www.example.com/doit/

Testing www.example.com/doit

done with .htaccess tester

Related