Search code examples
php.htaccess

How to setup a htaccess to a subfolder


I have this .htaccess right now:

DirectoryIndex index.php
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA]

It works if i setup my script on root folder, but if i create a new folder called 'api' and move all my script to there, does not work as expected and i see a blank page.

I modified the .htacess like this:

DirectoryIndex index.php
RewriteEngine on
RewriteBase /api/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /api/index.php [QSA]

Solution

  • Unfortunately, it is not entirely clear from the config, but there are two different path mechanisms:

    RewriteBase /api/
    

    This is "relative" to the request (or browser). i.e. https://example.com/api/

    However...

    RewriteRule ^(.*)$ /api/index.php [QSA]
    

    That is 'relative' to the server. So inside the server, you would need to have literally that file in a root directory called 'api'.

    In short, I believe that what you need is:

    RewriteRule ^(.*)$ api/index.php [QSA]
    

    (note the missing starting slash - which means path relative to the document root and not absolute server path)


    On a side-note, with RewriteBase /api/, it effectively means you do not care about other (undefined) root paths (e.g. /api2/xx won't be matched). Therefore there may be an even easier way to your original problem: just move your original .htaccess file into the api directory.