SoFunction
Updated on 2025-04-05

How to redirect 404 pages in Vue

Automatically generate the routing configuration of the vue-router module according to the pages directory structure.

To use routes between pages, we recommend using<nuxt-link> Label.

text

For me, Nuxt is one of the best software code I have ever used. It allows me to efficiently build website applications, whether they are SPA, SSR, or static sites, which is also the trend mentioned above by JAM Stack.

By the way, our website Vuedose is also a static site built using Nuxt.

However, most of the interesting techniques that you have learned have not been recorded and settled down. This is not possible. Now let’s share the first Nuxt technique.

If you are familiar with it, then you should know what the concept of pages is. Similarly, you should also know about this special Error Page, although it is placed in the Layouts folder, it is used as a page.

You can rewrite this default error page and customize it according to your needs, but what if we want a different form of expression?

In some cases, for example, when a user visits a page that does not exist, we want to redirect it to the home page of the website.

Here is a way: you can create it simplypages/*.vue Components to fulfill this requirement:

<!-- pages/*.vue -->
<script>
export default {
 asyncData ({ redirect }) {
  return redirect('/')
 }
}
</script>

In Nuxt, routes are defined by file naming. So when we create a*.vue The file is, we are actually in Vue Router Routes using wildcard characters.

Then we use the Nuxt contextrediect Method to implement redirection, whether it is on the client or on the server side.

We do this redirect in the asyncData method because we have a context there. However, we can achieve the same effect in the fetch method:

<!-- pages/*.vue -->
<script>
export default {
 fetch ({ redirect }) {
  return redirect('/')
 }
}
</script>

Go and use it, try to access any url that does not exist, and you should be able to see how it is redirected.

Summarize

The above is the method of Vue redirecting the 404 page in , which I introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!
If you think this article is helpful to you, please reprint it. Please indicate the source, thank you!