'After removing .php and adding / file not loading (object not found)

I was trying to remove the .php extension and add a / as normal websites have. Example http://example.com/category/.

I use .htaccess to remove .php. Here is the code:

RewriteEngine On
RewriteBase /

# hide .php extension snippet
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1/ [R,L]

# add a trailing slash    
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

This code does its task. It removes .php and adds / but the PHP page is now not loading.

This is a screenshot (file name test.php):

enter image description here

How to solve this?



Solution 1:[1]

It is because you're missing an internal rule to add .php silently to such redirect URIs.

You can add this rule in the end for that habndling:

RewriteEngine On
RewriteBase /

# hide .php extension snippet
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1/ [R=301,NE,L]

# add a trailing slash if needed
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteRule . %{REQUEST_URI}/ [L,R=301]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/$ $1.php [L]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1