Search code examples
apache.htaccessmod-rewriteurl-rewriting

How do I remove '.php' extension from URL without stopping the php from executing?


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]

Solution

  • Try this:

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

    This will internally redirect:

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

    But it will only redirect if the PHP file exists.