Same PHP file for an entire directory

Viewed 59

I have a directory on my site. Let's call it /dir/. I would like one PHP file to be in that directory (/dir/index.php), and I want any URL starting with /dir (aka /dir/any.file) to show the same file (/dir/index.php). (The file will parse the URL and return different information depending on the URL) I do not want the page to redirect, as that will make the URL change and then I wouldn't be able to parse it.

How would I do this? Should I just add a if statement at the beginning of my 404.php "if URL starts with /dir/, include /dir/index.php" or is that bad practice/is there a better way? I also would prefer not doing that as it would clutter up my error logs.

I assume it's something with .htaccess, right?

1 Answers

Could you please try following, written and tested with shown samples. Please keep your .htaccess file with same level of your dir folder(not inside dir folder please) and dir should have index.php file init. This will rewrite any url which starts with dir to index.php.

Also in the header of your webpage add this <base href="/"> so that your relative links can load from the correct location(in case of multilevel and preventing css/js files relative paths from broken links).

RewriteEngine ON
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(dir).*$ $1/index.php [NC,L]
Related