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?
5
Answers
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:
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 thelayouts 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.
If you need to provide custom routes to your users like
domain.com/<userID>
then putting a file with a name
_.vue
in your~/pages/
directory will not work, because you’ll need it for your custom user routes.For maximum flexibility use the layouts folder as mentioned by Dan
Create a file called
_.vue
atpages
directory with content: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
do not forget to creat an error page in layout folder
error.vue