What is the best way to always redirect domain.tld to www.domain.tld (or vice versa)?

I just realised that for a standard Grav installation, both domain.tld/some-page and www.domain.tld/some-page are valid routes. At least a while ago, this was considered bad for SEO as it was counted as “double content”.

I know I can fix this easily with a line or two in the .htaccess, but if that file gets updated, my changes will be lost. I thought about creating a plugin to sort this out, but that feels like overkill. Am I overlooking a simple way to achieve this, a setting or something? I’m sure a lot of people need this? :thinking:

I personally prefer .htaccess redirection in one or the other way, but if you set your preferred version (i.e. https://www.domain.tld/) in Admin/Config/System/Advanced/Custom base URL, you’ll get a rel=canonical link in the source code pointing to current page’s address according to it, so this should do the trick.

@Netzhexe, I doubt if it still matters for SEO…

If pages are accessible using both www and non-www and no canonical link is provided, Google will pick one as the canonical version and will only index that version.

Also, since popular browsers like Chrome and Safari are hiding www from the address bar, users will not be aware of www anymore.

If your theme uses <link rel="canonical" href="{{ page.url(true, true) }}" /> in template base.html.twig, setting custom_base_url will tell Google which version you prefer as canonical.

Google about 301 redirect:

Use 301 redirects to tell Googlebot that a redirected URL is a better version than a given URL. Use this only when deprecating a duplicate page.