I have an index.php
file in the DocumentRoot
of a virtualHost
in apache. It contains :
$path = $_SERVER['REQUEST_URI']
if($path == '/')
echo json_encode(some_data);
else if ($path == '/posts')
echo json_encode(another_data);
the thing is when I send a get request to /
it respond with the data I wanted, but when requesting /posts
or any endpoint other than /
, the server respond with not found page.
How can I make it use index.php
for every request that virtualhost ?
I want all the requests to be handled by index.php
2
Answers
WordPress deals with that by adding this to the
.htaccess
file:Basically, you need to redirect all requests to index.php, but not using a 301 or 302, just rewriting. The
RewriteCond
lines are to make it so users can still access other files directly if they exist. You may not need those in your implementation.Here’s an explanation of the code:
RewriteEngine On
turns on the rewrite engine 🙂RewriteBase /
Just makes sure we’re starting from the document rootRewriteRule ^index.php$ - [L]
is a rule that does nothing if the request is for index.php. the [L] means no more rules will be processed.RewriteCond
lines make sure that there’s not a matching file (1st line) or directory (2nd line) for the request. If there is, then the followingRewriteRule
won’t take effect, and the server will serve up that file or directory. Otherwise:RewriteRule ^index.php$ - [L]
will rewrite the request to /index.php, making your script handle the request without redirecting the user’s browser to index.php.If there is no
.htaccess
file, you’ll need to add one, or add the rules to the conf file for this virtualhost. The conf file will also need to allow overrides to see the .htaccess file:You can use FallbackResource:
Set it in your virtual host settings or in an
.htaccess
file.