# Automatically redirect /index.php files to their URL directory with .htaccess

The requirements:

• Work inside .htaccess (preferably via mod_rewrite)
• Redirect requests from /any/directory/index.php to /any/directory/
• Make sure that /index.php-with-stupid-stuff-here does not get rewritten
• Add trailing slash to directories, /another/directory becomes /another/directory/

Also note that:

• The ideal scenario would be to use manual 301 redirects, but this is a case where there are far too many directories to do that for individually.
• Internal linking is clean (always goes to the right place), so this is a just-in-case solution. (But others who find this question might be in a different situation.)

DaveRandom helped me revise my solution, resulting in…

RewriteEngine On
RewriteCond %{THE_REQUEST} (?:/[^/]*)*/index\.php[?#\ ]
RewriteRule .* %{REQUEST_URI}/../ [L,R=301]


The basic idea behind it is that by using %{THE_REQUEST} in a RewriteCond you are looking at the actual URI requested by the user before any file system mappings, alias, other rewrite rules etc. were applied.

This is important, because if you just look at the request-URI in a RewriteRule you will almost definitely end up in a redirect loop.

Questions:

• Is that solid, correct code?
• Anything else that should be added, or taken into account?
• Or, considering best practices, is there a better way entirely?
• Looking for nearly the exact same thing. Any success? – Art Geigel Apr 30 '20 at 16:32
• @ArtGeigel, I ended up using that code. I don't remember the outcome though. Does it work for you? – Baumr May 11 '20 at 20:21
• I ended up figuring out my problem that initially prompted me to land on this page looking for answers. In my situation there was a parent directory housing an abandoned Wordpress installation (that I had completely forgotten about!) with a custom .htaccess that was conflicting with things I was trying to do in a sub-directory. Once I removed that then things worked fine for my needs. Others who have come to this page searching Google for similar answers consider looking above the directory you’re working with and carve out exceptions in parent .htaccess files for your folder. – Art Geigel May 12 '20 at 15:14
• @ArtGeigel, thanks for sharing! Consider writing an answer to this if you think it's helpful! I can upvote and mark it – Baumr May 14 '20 at 20:37