Configure URL rewrite for Google Cloud Static Site Load Balancer

Configure URL rewrite for Google Cloud Static Site Load Balancer

Published on 2025-04-14

A common way to host static websites for pennies is through using AWS CloudFront and AWS S3. In such a configuration, it is fairly simple to do URL rewriting if you follow URL best practices and also don't want to do "everything is a path with index.html", that is, to rewrite pages/blog to pages/blog.html so that page gets served instead of pages/blog directory contents.

However, if you use Google Cloud, it is a bit more convoluted to accomplish. In this article, I give a quick example on how to handle such a rewrite.

Rewrite URL in Google Cloud

To begin with, Google's set up for a static website requires using a load balancer to serve a static bucket backend. I won't go to the details which architecture makes more sense, and I won't also go to explaining how to set up the basic setup as Google has good documentation on that area.

So I assume you have setup your static website serving in your Google Cloud Project using the Google Cloud documentation. Now, you want to do the setup described in the intro of this article: when a user accesses yourdomain.com/pages/blog, you want to serve the Blog page, not the contents of the blog directory.

This is the rewrite rule setup for the load balancer:

Hosts
yourdomain.com
Default action
Route traffic to a single backend
Backend name
YOUR-BACKEND-BUCKET-NAME

And the actual rule:

defaultService: projects/YOUR-PROJECT-ID/global/backendBuckets/YOUR-BACKEND-BUCKET-NAME
name: matcher1
routeRules:
- description: SSGService
  matchRules:
  - pathTemplateMatch: /pages/{pages=**}
  priority: 1
  service: projects/YOUR-PROJECT-ID/global/backendBuckets/YOUR-BACKEND-BUCKET-NAME
  routeAction:
    urlRewrite:
      pathTemplateRewrite: /pages/{pages}.html

You would obviously replace the yourdomain.com with your actual domain, the YOUR-BACKEND-BUCKET-NAME with the name of your Load Balancer backend bucket name, and the YOUR-PROJECT-ID with your project ID.

Now, the rule above is not limited to just this use case. In fact, the rewriting system is quite powerful. I come from running my own web servers, and the syntax for the Google Cloud load balancer rewriting wasn't super obvious from the get go. Hopefully with the sample above you can take more advantage of this powerful (yet expensive) system.