2

Instead of a standard 404 error page, I want to send 404s to the homepage and can't seem to get this working right.

If I add {% redirect '/' %} in my 404.html template, that works except it gives a 302 found code instead of a 404.

If I change it to {% redirect '/' 404 %} I get the correct 404 code but just a white screen instead of the homepage.

I've also tried adding ErrorDocument 404 / to the .htaccess file, but that doesn't take effect as I think the Craft 404 mechanism overrides that.

Can anyone help? Thanks.

  • How about craftcms.stackexchange.com/questions/5242/… ? – Steven Grant Apr 18 '18 at 13:50
  • Thanks Steven. I had seen that, but the client would prefer to just go direct to the homepage. I suppose I could try a meta refresh after 0, but I remember they could cause SEO issues back in the day, so was hoping there was a cleaner way & I was just missing something? – Tidy Apr 18 '18 at 14:07
4

404 isn’t a valid redirect status code, which is why {% redirect '/' 404 %} isn’t working correctly.

It sounds like you want to:

  • first issue a 301 or 302 redirect to the homepage
  • then serve the homepage, but with a 404 status

If I’m understanding you correctly, even if you could pull it off (maybe doable with a query string or something stored on the session), that would be bad for a couple reasons:

  • the actual not-found resource is returning the wrong status code (301/302 instead of 404)
  • now the homepage (a valid resource) is also returning the wrong status code (404 instead of 200)

The biggest issue is the 2nd one, as it would have devastating SEO consequences. Any time Google hits a missing resource and is redirected back to the homepage, it will start remembering that your homepage doesn’t exist.

A better solution would be to keep the URL pointed at the missing resource (so no redirect response), but to just render your homepage via the 404 template.

That should be as simple as creating a 404.html template with this:

{% include "index" %}

(or whatever your actual homepage template is called.)

If you have a Homepage Single section, you may need to pass that in as well:

{% include "index" with {
    entry: craft.entries.section('homepage').one()
} %}

(replace .one() with .first() if this is for Craft 2.)

  • Perfect! Many thanks for the quick response Brandon and for explaining so clearly. – Tidy Apr 18 '18 at 15:49
  • Just to add to what Brandon wrote, you can do more than just 404 templates, too. More here: Handling Errors Gracefully in Craft CMS – andrew.welch Apr 18 '18 at 20:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.