Search code examples
apachevue.js.htaccessnuxt.js

How to manually generate pages in Nuxt router with a 404 page fallback for .htaccess


I'm trying to create an SSG site with Nuxt.js. When I access a route that isn't set in the generate property of nuxt.config.js, I want to display the contents of a 404 page without changing the URL.(using htaccess)

The following is the site under construction

http://we-are-sober.d3v-svr.com/xxxx

This is working as expected.

http://we-are-sober.d3v-svr.com/user/xxxx

This does not work as expected.

The contents of page 404 are displayed for a moment, but soon after that, the process based on the dynamic route of "user/_id.vue" is executed.

The point of the problem is that the non-existent route behaves as if it exists. Does anyone know how to solve this problem?

Here is the source code. https://github.com/yhirochick/rewrite_test

404.vue

https://github.com/yhirochick/rewrite_test/blob/master/pages/404.vue

user/_id.vue

https://github.com/yhirochick/rewrite_test/blob/master/pages/user/_id.vue

nuxt.config.js

https://github.com/yhirochick/rewrite_test/blob/master/nuxt.config.js#L43-L45

.htaccess

https://github.com/yhirochick/rewrite_test/blob/master/static/.htaccess

I am Japanese. The above text is based on Google Translate. It may be difficult to understand, but thank you.


Solution

  • It's a tricky way, but I've found the code that works as I want.

    https://fes.d3v-svr.com/users/xxxxxx It's works that I expect.

    • User xxxxxx doesn't exist
    • Display 404 page
    • The URL /users/xxxxxx as it is

    First, simply set .htaccess to rewrite non-exist page to 404 page

    ErrorDocument 404 /no-user/index.html
    

    Only above, Nuxt execute base on URL /users/xxxxxx/ and re-render the page as "UserXXXXXX" even he is not exist.

    To avoid this, users/_id.vue is like bellow.

    template

    <template>
      <div v-if="ssr">User name: {{ user.name }}</div>
    </template>
    

    script

    <script>
    export default {
      asyncData({ payload }) {
        return { user: payload, ssr:true }
      },
    }
    </script>
    

    It seems to be if a template is empty, nuxt will not execute the script depends on the URL.

    It's very tricky, so I'll continue to how it is works.