What seems like an easy feature to add to a website running on a standard web environment can be a little challenging in a Cloud environment. My retro gaming website, Atari Gamer
, runs in AppEngine and uses Silex/Symfony as its web application framework. I noticed that there have been requests coming through to the WWW domain, which I wanted to be redirected to the naked domain so had to find a solution.
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.
A quick disclaimer...
Although I put in a great effort into researching all the topics I cover, mistakes can happen.
Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.
All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle).
Use of any information contained in this blog post/article is subject to this disclaimer