<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # Redirect non-existent pages to their folder's index.php
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^([^/]+)/([^/]+)\.php$ /$1/ [L,R=301]

  # Redirect to root index.php if folder index.php doesn't exist
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^([^/]+)/?$ /index.php [L,R=301]
</IfModule>