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

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

Mike5050
1#
Mike5050 Published in 2017-12-07 05:10:26Z

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!

Ben
2#
Ben Reply to 2017-12-07 05:45:21Z

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;
        }
    }
?>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.311359 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO