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