Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

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.
 PHP
$app->before(function (Request $request) {
$requestUri = $request->getRequestUri();
$httpHost = $request->getHttpHost();
if (AG_DEBUG) {
error_log('>> REQUEST ' . $requestUri);
}
if (substr($httpHost, 0, 4) == 'www.') {
$url = $request->getScheme() . '://' . substr($httpHost, 4) . $requestUri;
if (AG_DEBUG) {
error_log('<< REDIRECT WWW TO NAKED ' . $url);
}
return new RedirectResponse($url, 301);
}
});




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...
 Console
>> REQUEST /lynx/game/APB/1513416078
<< REDIRECT WWW TO NAKED http://localhost/lynx/game/APB/1513416078
>> REQUEST /lynx/game/APB/1513416078


Working as expected! The code is packaged as a before middleware to make sure it runs prior to any other request processing is performed.

-i

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.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.