.htaccessphar

.htaccess - serve requests on a .phar file if found, otherwise serve on index.php


I want to deploy a web application packaged in a .phar file and serve requests from it like I actually do from an index.php file in $_SERVER["DOCUMENT_ROOT"].

The default mod_rewrite in Apache goes like this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

If I wanted to do the same with a .phar file I suppose (although I may be wrong, so any direction would be more than welcome) I could do it like this:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /application.phar [L]
</IfModule>

I could always have two .htaccess files and use the appropiate one depending on the type of deployment but I would like to support BOTH strategies if possible. Whether I want to run an application packaged or unpackaged, I want to be able to re-use the .htaccess file between projects but taking into account the packaged version should be the preferred way.

How can I combine these two different rules in just one?


Solution

  • Have it like this:

    <IfModule mod_rewrite.c>
    
        RewriteEngine On
        RewriteBase /
    
        # ignore all existing files/directories from rewrite
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]
    
        # if application.phar exists then use it
        RewriteCond %{DOCUMENT_ROOT}/application.phar -f
        RewriteRule ^ application.phar [L]
    
        # otherwise use index.php
        RewriteRule ^ index.php [L]
    
    </IfModule>