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

Skip down to comments...
Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
 
comments powered by Disqus
Other posts you may like...