PHP get public facing base directory from URL

I would like to be able to tell what the base directory of a site is automatically. Say I have a website in this location on a Unix machine:


And it’s publicly accessible here:

I would like to be able to move the website from “temp” to the root of the site without having to manually change my php configuration files in my framework.

I guess what I need is the public facing directory of the index.php file, so say I have a .htaccess rewrite rule that means:

.. will load the index.php file in the root and will return the page at /pages/page, I would need the “base directory” of the site to return “” (An empty string) because the site belongs directly after the domain name. But then say I put the site inside a directory like:

I would need the “base directory” to return “directory” so I can use it within the code elsewhere.

I am very sorry if this sounds vague and I will happily explain more if needed but any help will be greatly appreciated!

Source: .htaccess

1 Comment

  1. Digin Dominic

    You can use this code in your DOCUMENT_ROOT/.htaccess file:

    RewriteEngine On

    RewriteCond $0#%{REQUEST_URI} ^([^#]*)#(.*)1$
    RewriteRule ^.*$ - [E=BASE:%2]

    It compares REQUEST_URI variable (which is the complete URL) with the URI matched by RewriteRule (which is relative to current path) and gets differential in %{ENV:BASE} variable.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.