Aug 7, 2014

How to set default env to develop for symfony project

After you created a symfony project, including frontend app, when visit the local site url of the project, you would do want it showing the symfony debug toolbar by default.

This means you don't need to append frontend_dev.php to visit the develop env.

Following tricks on site definition do help on this:

1. Edit your apache virtual host definition for the project website, add this line:

SetEnvIf Request_URI ".*" PROJECT_ENV=dev

So your virtual host configuration will look like:

<VirtualHost localhost:80>
  ServerName yoursite.localhost
  ServerAlias *.yoursite.localhost *.yoursite.local-site
  DocumentRoot "__your_symfony_project_doc_root__"
  DirectoryIndex index.php

  # Set the project environment mode: dev, prod
  # Note: This is a bit of hack because SetEnv won't let var values show up in rewrite conditions.
  SetEnvIf Request_URI ".*" PROJECT_ENV=dev

  <Directory "__your_symfony_project_doc_root__">
   AllowOverride All
   Allow from All
  </Directory>
  Alias /sf "__your_symfony_project_path__/lib/vendor/symfony/data/web/sf"
  <Directory "__your_symfony_project_path__/lib/vendor/symfony/data/web/sf">
   AllowOverride All
   Allow from All
  </Directory>
</VirtualHost>

2. Edit your project website .htaccess file as below, attention to bold lines:

# For security reasons, Option followsymlinks cannot be overridden.
#Options +FollowSymLinks +ExecCGI
Options +SymLinksIfOwnerMatch +ExecCGI

<IfModule mod_rewrite.c>
  RewriteEngine On

 # For testing setting the project env, uncomment next line.
#  SetEnvIf Request_URI ".*" PROJECT_ENV=prod


  SetEnvIf Host prod\..* PROJECT_ENV=prod

  # uncomment the following line, if you are having trouble
  # getting no_script_name to work
  #RewriteBase /

  # we skip all files with .something
  #RewriteCond %{REQUEST_URI} \..+$
  #RewriteCond %{REQUEST_URI} !\.html$
  #RewriteRule .* - [L]

  # we check if the .html version is here (caching)
  RewriteRule ^$ index.html [QSA]
  RewriteRule ^([^.]+)$ $1.html [QSA]
  RewriteCond %{REQUEST_FILENAME} !-f

  # no, so we redirect to our front web controller

  # Below we define conditional rules that will go controller based on env
  # The default will be dev.

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{ENV:PROJECT_ENV} =prod [NC]
  RewriteRule ^(.*)$ index.php [QSA,L]

  #RewriteCond %{ENV:PROJECT_ENV} =dev [NC]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ frontend_dev.php [QSA,L]
</IfModule>

3. Restart apache service, enjoy your developing!