Mike5050
Mike5050

Reputation: 605

How can I mod rewrite all traffic to index.php but also to a backend directory?

I have a .htaccess as follows:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^public
    RewriteRule ^(.*) index.php [L]
</IfModule>

My directory is set up as follows:

root directory:
  html:
      index.php
      .htaccess
  server (code):
      site:
          index.php
          test.php

Requests go into html/index.php, and then the server gets initiated in the backend. Calling $_SERVER['REQUEST_URI']; yields the following for http://localhost/

Request URL : /index.php

This is correct, because I can then add on site/index.php. However, I want to also do http://localhost/test and have it changed to /site/test.php. The following is what happens when calling $_SERVER['REQUEST_URI']; for http://localhost/test

Request URL : /testindex.php

What should happen is Request URL : /test so then I can add on the site/test.php myself.

Thank you!

Upvotes: 0

Views: 43

Answers (1)

Ben
Ben

Reputation: 5129

Files / Directories cannot be accessed outside the document_root. The simple solution is to update the index.php as a router. Then the router needs to include the corresponding files, if it exists. Otherwise you need to handle the file not exists situation, such as response 404 error.

You may need to update this .htaccess to redirect all the request to index.php:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^public

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    RewriteRule ^$ index.php [L]
    RewriteRule ^(.*) index.php?route=$1 [QSA,L]

</IfModule>

Then, you can parse the route in index.php:

<?php
    if (isset($_GET['route'])) {
        $route = $_GET['route'];
        if (file_exists(__DIR__.'/../site/' . $route)) {
            include __DIR__.'/../site/' . $route;
        }
    }
?>

Upvotes: 1

Related Questions