Home > database >  .htaccess script to remove .php extension prevents index.php access
.htaccess script to remove .php extension prevents index.php access

Time:01-05

I want to use the following script to remove the .php extension when accessing my web pages. However, this prevents me from accessing the index.php of the website by simply going to the main website URL.

How can I fix this issue so that both .php extensions are removed, and I can access the index.php by just typing out the website name?

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

CodePudding user response:

This is a slightly modified version of what @DerLola posted in his answer which is generally correct, but contains some oversight. Unfortunately he did not react to me pointing out that issue which is why I now decided to post this variant. All the credit belongs to him, obviously!

RewriteEngine On
RewriteRule ^/?$ - [END]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ %{REQUEST_URI}.php [NC,L]

This assumes that your setup already takes care to execute index.php when the base URL is requested. This might happen by means of the DirectoryIndex directive or by some other rewriting rules implemented by your application logic.

CodePudding user response:

You can add a new rule above your current rule to check for an empty path (the root) and rewrite it to index.php like so:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^$ index.php [NC]
RewriteRule ^([^\.] )$ $1.php [NC,L]
  •  Tags:  
  • Related