Zakriya Bilal Zakriya Bilal - 10 months ago 88
Apache Configuration Question

Some Pages without .php extension Mod Rewrite

So I have this site, It has a directory structure like this:


  1. index.php

  2. page1.php

  3. page3.php

  4. folder/index.php

  5. example/index.php

  6. page4.php



I want to remove the .php file extension only from the URLs that are not in a subdirectory. Because If I remove the .php from all the URLS like so:

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


The files in subdirectories like which were previously accessible by this URL: https://example.com/folder now give a 404 unless I enter index.php or file name at the end of it.

So I want to know the following:


  • How can I remove .php from only a select few targeted files so that the files in a folder/subdirectory are not affected?

  • How can I change the above .htaccess code so that it does not target the files that are in a folder/subdirectory?


Answer Source

If you want to add .php extension to only files in site root then use:

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

Here negated character class [^/.]+ will match only file in current directory as it matches 1 or more characters that are not / and .

However if you want to correctly add .php to all files then use this rule:

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download