Home > Net >  After removing .php and adding / file not loading (object not found)
After removing .php and adding / file not loading (object not found)

Time:02-18

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?

CodePudding user response:

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]

CodePudding user response:

After a few research that is actually working in my case is given below.

It removes the .php extension and adds / at the end of the URL.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-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]

Output:

enter image description here

Reference: https://alexcican.com/post/how-to-remove-php-html-htm-extensions-with-htaccess/

  • Related