skip to Main Content

I have a Vue SPA, in my localhost when I start project by npm run serve and try to access a route that I have not defined takes me to 404, this is my vue router configuration

{
    path: '/',
    name: 'MainLayout',
    component: () => import('../layouts/MainLayout.vue'),
    meta: {
        middleware: 'translation'
    },
    children: [
        {
            path: '',
            name: 'Index',
            component: () => import('@/application/views/Index.vue')
        },
       // other routes
        {
            path: '/:catchAll(.*)',
            component: import('@/application/views/404Page.vue'),
            name: 'NotFound'
        }
    ]
},

In my server that I use nginx with this configuration it does not but I can see <Header> or <Footer> components that are defined in my MainLayout

server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/nginx/certs/fullchain.pem;
    ssl_certificate_key /etc/nginx/certs/privkey.pem;

    location / {
        root /usr/share/nginx/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }
}

MainLayout.vue

  <div class='w-full min-h-screen'>
    <Header class="flex-shrink-0"/>
    <router-view class="flex-grow"/>
    <Footer class="flex-shrink-0"/>
  </div>
</template>

I tried this configuration in my nginx conf file but doesn’t work

server {
    listen 80;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/nginx/certs/fullchain.pem;
    ssl_certificate_key /etc/nginx/certs/privkey.pem;

    access_log /var/log/nginx/application_access.log;
    error_log /var/log/nginx/application_error.log;

    location / {
        root /usr/share/nginx/html;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    error_page 404 /index.html;
    location = /index.html {
        root /usr/share/nginx/html;
        internal;
    }
}

2

Answers


  1. Chosen as BEST ANSWER

    The problem was on this line:

    component: import('@/application/views/404Page.vue')

    It should be like this:

    component: () => import('@/application/views/404Page.vue')


  2. You have to choose between frontend routing (vue-router) or backend routing (nginx).

    With your config Nginx will redirect everything to index.html at first hit.

    Then you use a frontend router with a catchAll route so routing is done entirely inside your browser. Nginx will never be queried after that first hit.

    If you want nginx to handle the 404 you have to remove the catchAll from your frontend routing (but it would be useless as 404 is again using index.html).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search