[Tip] .htaccess rules for frontend application + symfony backend API

Problematic

When building a frontend application (angularjs) backed by a API made with symfony, hosted on the same server/domain name, I suffered a few difficulties.
Here the .htaccess rules to make it work :

Configuration

  • all requests beginning by /api to be redirected to /app.php
  • all other requests to be redirected to /index.html

.htaccess file

The complete .htaccess file, the steps from the "official" file and some explanations are below.

DirectoryIndex index.html

<IfModule mod_rewrite.c>
    RewriteEngine On

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

    # If the requested filename exists, simply serve it.
    # We only want to let Apache serve files and not directories.
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule .? - [L]

    # Rewrite to API
    RewriteRule ^api/(.*) /app.php/api/$1 [L]

    # Rewrite all other queries to the front controller.
    RewriteRule .? %{ENV:BASE}/index.html [L]
</IfModule>

Steps

I used the symfony2.4 .htaccess as base file

Change DirectoryIndex to index.html

    DirectoryIndex index.html

Comment the "remove app.php" part

    #RewriteCond %{ENV:REDIRECT_STATUS} ^$
    #RewriteRule ^app\.php(/(.*)|$) %{ENV:BASE}/$2 [R=301,L]

Add /api rewrite rule

    RewriteRule ^api/(.*) /app.php/api/$1 [L]

And change the last rule

    RewriteRule .? %{ENV:BASE}/index.html [L]