My root directory has the following structure:
/assets/
/pages/
/.htaccess
index.pp
Inside /pages/
I have PHP files. For example,projects.php
. I tried writing in .htaccess
rules to take the URL example.com/projects
and open the file from /pages/projects.php
and it worked with the following:
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} . [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# No file extension on request then append .php and rewrite to subdir
RewriteCond %{REQUEST_URI} /(.+)
RewriteRule !\.[a-z0-4]{2,4}$ /pages/%1.php [NC,L]
# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /pages/$1 [L]
My problem here is that when I go to the root example.com
, instead of opening index.php
it’s opening the /pages/
directory, but if I go explicitly to example.com/index.php
it works.
I don’t want index.php
to be shown in the URL, so I need to exclude the root from my rule and make it open index.php
while the URL stays example.com
.
# All remaining requests simply get rewritten to the subdir RewriteRule (.*) /pages/$1 [L]
To exclude "the root" being rewritten to /pages/
(and serve index.php
from the root instead) you can simply change the quantifier in the last rule from *
(0 or more) to +
(1 or more) - so that it doesn't match requests for the root (an empty URL-path in .htaccess
).
In other words:
RewriteRule (.+) /pages/$1 [L]
Incidentally, you have already done something similar in the preceding rule/condition by using +
in the CondPattern, ie. RewriteCond %{REQUEST_URI} /(.+)
.