Home > Software engineering >  How do I remove '.php' extension from URL without stopping the php from executing?
How do I remove '.php' extension from URL without stopping the php from executing?

Time:01-16

I have removed the '.php' file extension the URL in the .htaccess file, however, it seems to prevent my php code from running.

Could someone please suggest a way that I can get this to work?

RewriteEngine On
RewriteCond %{THE_REQUEST} \s/ (. ?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]
RewriteCond %{THE_REQUEST} \s/ (. ?)\.html[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]
RewriteCond %{THE_REQUEST} \s/ (. ?)index[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

CodePudding user response:

Try this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^/?$ /index.php
RewriteRule ^(.*)$ $1.php [L]

This will internally redirect:

https://yourwebsite.com/ -> index.php
https://yourwebsite.com/hello -> hello.php
https://yourwebsite.com/world -> world.php

But it will only redirect if the PHP file exists.

  • Related