Single Apache Virtualhost for Serving Angular Front End with a Dynamic API
Oct 11, 2025
Because Angular, on production, is basically a set of static files, and a dynamic API relies on Apache serving only one static file (e.g. index.php), and the two sets don't collide, we can serve them from the same virtualhost with a small bit of care. To do so, we use standard apache rewrite rules to redirect all requests that don't resolve to a real static file to the API's single static file (again, e.g. index.php). Otherwise we just serve the static file (angular ts or json, image, css, etc).
Where we need to be careful is in the deployment. I tend to lock in the API first and it stays, more or less, fixed during development of the front end. This is what I initially clone into my production source tree. Then I have a CI/CD pipeline that builds my front end, tests it, and if all is well, I use rsync to sync it to my document root in the source tree. The rsync command deletes old files with the exclusion of the 3 static files that my API provided:
rsync -e ssh -avz \
--delete \
--exclude index.php \
--exclude favicon.ico \
--exclude robots.txt \
dist/my_project/browser/ my-server.com:/var/www/my_project/public/
My virtualhost configuration uses standard rewrite rules as follows:
<directory>
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# The following rewrites all other queries to index.php. The
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting, the base path will be prepended to
# allow proper resolution of the index.php file; it will work
# in non-aliased environments as well, providing a safe, one-size
# fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)(.+)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}index.html [NC,L]
</directory>
tags:angular , apache , back end , front end , laminas , laravel
