If Google Cloud CDN and Varnish Cache are not enough, then it’s time to DIY

Advanced Caching Part 2: Google Cloud CDN and Apache

Waheed Brown
Google Cloud - Community
2 min readAug 21, 2019

--

In part 1, Google Cloud CDN and Varnish, we learned to cache dynamic responses. Here in part 2, we remove Varnish from the picture completely and do it all ourselves. Assuming Google Cloud CDN is up and running, we can use Apache to modify the HTML response before it gets cached.

1. Apache Module mod_substitute
Enable Apache Module mod_substitute on a Google Compute Engine (GCE) virtual machine (VM)

sudo a2enmod substitute
sudo service apache2 restart

NOTE: The above terminal commands are for Ubuntu Linux

2. Add the desired JavaScript code in a .js file

Make a .js file to hold your desired JavaScript code (run on the end users web browser)

3. Use Apache Substitute to Insert a <script> Tag
Apache’s mod_substitute module allows you to write markup rules

vim /etc/apache2/ports.conf

In the ports.conf file, these markup commands let you leverage the Linux substitute command, “s”

Put the JavaScript file from step 2 inside the script tags

Use the Linux substitute command, “s”, to insert a JavaScript file into the HTML response

4. Make Rules for Different Directories and Files
Notice that the above substitution in the <Location> tag
The substitution is for all web pages in the web server’s root directory
Use additional <Location> tags for specific web directories and files

5. Response Body Modification Works!
The <head> tag in the HTML response was modified by Apache
It now includes a <script> tag referencing your JavaScript file

The <head> tag was updated and this modified HTML response will be cached by Google Cloud CDN

This is a great way to populate dynamic content in a cached web page*

*NOTE: Make sure to match your content’s expiration times with the life cycle of your .js file changes

--

--