Monday, December 05, 2011

Rewrite Rulez!!!

While common Web frameworks provide a set of mod_rewrite rules in their default application, it is left to the developer to align these rules according to the Apache host configuration. For example if you use an alias when setting up a Symfony application then a RewriteBase directive must be added to the application rules. This is a common change that is required to keep the original list (provided by the framework) as is.

To this end a post-deployment action can be added to fix the RewriteBase directive in the '.htaccess' file. In a previous post, application deployment scripts were used to help chmod application's resources. This time I am going to use deployment hooks to modify the RewriteBase directive automatically after deploying the Symfony2Cloud application.

In the deployment script you can find this code:

// get application location
$appLocation = getenv('ZS_APPLICATION_BASE_DIR');
// modify htaccess
$htaccess_file = $appLocation . '/web/.htaccess';
$explode = explode ( '/', $appLocation );
$appname = $explode [sizeof ( $explode ) - 2];
$content = file_get_contents ( $htaccess_file );
$content = str_replace ( '<application-name>', $appname, $content );
file_put_contents ( $htaccess_file, $content );

In details: The application location is used to resolve its alias. Then the alias name is used to replace the .htaccess file content so instead of "RewriteBase /<application-name>" it will show up as "RewriteBase /Symfony2Cloud".

Assuming that you use Zend SDK and the following deploy command:

zend deploy application -r git://

Symfony2Cloud is now deployed and ready to use with this .htaccess:

<IfModule mod_rewrite.c>
 RewriteBase /Symfony2Cloud

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ app_dev.php [QSA,L]

No comments: