Add redirects for www or non-www #12
Replies: 5 comments 6 replies
-
Hi @matthewstick, this is on our list to have a general redirect offering that would cover this scenario as well. We can keep this open for discussion/implementation when the time comes :) |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
I want to upvote this as well. Having both www and non-www available actually gives a negative impact on SEO, marketing agencies don't like it either, google doesn't like it, but currently there is no easy way to redirect www to non-www on a 301. Bad SEO or duplicate content, can have a very negative impact on the business. |
Beta Was this translation helpful? Give feedback.
-
This is on our short-list, but in the meantime, you can achieve this via <?php
// config/app.web.php
return [
'on beforeRequest' => function (\yii\base\Event $event) {
$fromHost = 'mysite.com';
$toHost = 'www.mysite.com';
if (Craft::$app->getRequest()->hostName !== $fromHost) {
return;
}
Craft::$app->getRequest()->setHostInfo("https://$toHost");
Craft::$app->getResponse()
->redirect(Craft::$app->getRequest()->getAbsoluteUrl(), 301)
->send();
$event->handled = true;
Craft::$app->end();
},
]; |
Beta Was this translation helpful? Give feedback.
-
edit: for the before I was applying the change to I noticed with the above with craft cloud I would get an issue when building the container (or running any console commands) and had to modify the above block to first include: $request = Craft::$app->getRequest();
if (!$request instanceof craft\web\Request) {
return;
} (and then optionally just replacing any other calls to getRequest with the already fetched request object). |
Beta Was this translation helpful? Give feedback.
-
Usually we just run a site on www or non-www. We don't want to run the site on both. I don't see a way for us to "strip wwws" or "add wwws" or "leave both / ignore" in our domains.
Would be great if this was a feature, since it is something we need to do for every site.
In the meantime, I added php code in the index.php to handle this - but this is not ideal.
$host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST'];
if (substr($host, 0, 4) === 'www.') {
$nonWwwHost = substr($host, 4);
$requestUri = $_SERVER['REQUEST_URI'];
$newUrl = 'https://' . $nonWwwHost . $requestUri;
header('Location: ' . $newUrl);
exit;
}
Beta Was this translation helpful? Give feedback.
All reactions