Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt 404 error page should redirect to homepage

I am looking for a way to always redirect to homepage when a page doesn't exist using Nuxt.Js.

Our sitemap generation had some problems a few days back and we submitted wrong urls that do not exist. Google Search Console shows a big number of 404 and we want to fix them with 301 redirect to homepage.

I tried this

created() {
    this.$router.push(
      this.localePath({
        name: 'index',
        query: {
          e: 'er'
        }
      })
    )
  }

and although the page redirects to homepage successfully I think Google will have problems with this since the pages initially renders with 404.

I also tried this

  async asyncData({ redirect }) {
    return redirect(301, '/el?e=rnf')
  },

but didn't work (same with fetch)

Any ideas on a solution to this?

like image 619
mauxtin Avatar asked Jan 31 '19 11:01

mauxtin


3 Answers

Never redirect to home if page is not found as you can see in this Google's article: Create custom 404 pages

instead, redirect to 404 error page

Just use error

 async asyncData({ params, $content, error }) {
    try {
      const post = await $content('blog', params.slug).fetch()
      return { post }
    } catch (e) {
      error({ statusCode: 404, message: 'Post not found' })
    }
  }

do not forget to creat an error page in layout folder error.vue

like image 137
Leonardo Cavalcante Avatar answered Sep 27 '22 21:09

Leonardo Cavalcante


You are able to create a default 404-page in nuxt - just put a file with a name _.vue in your ~/pages/ dir. This is your 404-page :)

or you can use another method to create such page: https://github.com/nuxt/nuxt.js/issues/1614 but I have not tried it

Then add a simple 404-redirect-middleware to this page:

// !!! not tested this code !!!
middleware: [
  function({ redirect }) {
    return redirect(301, '/el?e=rnf')
  },
],
like image 44
gleam Avatar answered Sep 27 '22 21:09

gleam


Personally I would advise to create a 404 page which provides a better user experience in comparison to being redirected to a homepage and potentially being confused about what happened.

In order to create a custom error page, just create error.vue file in the layouts folder and treat it as a page. See the official documentation. We've implemented this plenty of times and Google has never complained about it.

Still, gleam's solution is clever and if it serves the purpose, very well. Just wanted to point out another solution.

like image 25
Dan Avatar answered Sep 27 '22 19:09

Dan