I do not like to ask this question because it was asked a million times, but the answers never seem to be satisfactory, and most threads seem to be left without an accepted answer.
Here's exactly what I need to do (bad URLs intentionally due to low karma):
http://example.com/file.php redirects to http://example.com/file/
http://example.com/file should also be redirected to http://example.com/file/
http://example.com/asdfsadf and http://examplecom/file/asdfasdf should go to page 404
Here is the htaccess magic that I put together with the posts here and elsewhere. It seems to work (unlike most abandoned threads on a topic where there is always strange behavior).
RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^([^/]+)/$ $1.php RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$ RewriteRule (.*)$ /$1/ [R=301,L] RewriteCond %{THE_REQUEST} ^[AZ]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/ RewriteRule ^(([^/]+/)*[^.]+)\.php http://example.com/$1 [R=301,L]
As I said, as far as I can tell, this works great even with subdirectories. Can any of the knowledgeable people tell me if I missed something. Is it possible to improve or reduce?
For what it's worth, I also delete www:
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC] RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]
Everything seems to be fine. It turns on after other parts. Is this the best order?
Thanks to everyone, I hope that we get a good, reliable answer for this, because there are many bad ones.