Usually this would have been done in .htaccess, but AppEngine did not support that and a programmatic solution was required. The Symfony cookbook was a good starting point.
The code for this feature was quite simple. I've also added extra debug code to make sure it was working as expected. Feel free to remove "if (AG_DEBUG)" blocks or define the AG_DEBUG variable if you want to keep them.
What the code does is first get the request URI and from that it gets the HTTP host. It checks if the host name starts with 'www.' and if it does, the hostname is stripped off the first 4 characters i.e. 'www.' and a 301 redirect request is issued. The scheme i.e. HTTP or HTTPs, is retained.
When testing it out with a www domain (www.local) the console output looks like this...
Working as expected! The code is packaged as a before middleware to make sure it runs prior to any other request processing is performed.