Home > Mobile >  redirect to a single file in apache
redirect to a single file in apache

Time:02-24

I'm 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 ?

CodePudding user response:

WordPress deals with that by adding this to the .htaccess file:

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

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.

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:

<Directory "/path/to/document/root">
    AllowOverride All
</Directory>

CodePudding user response:

You can create custom 404 page in Apache :

ErrorDocument 404 /path/to/yourAwesome404File.html

Or if you want a specific answer to your question, you can use else :

if($path == '/index.php' or $path == '/'){
    //
} else {
    // 404
}
  • Related