Search code examples
vue.jsnginxvue-componentvuetify.jsstatic-files

How can I set up nginx to solve 404 not found on static file vue?


I using nginx to run my project. So I install nginx to my localhost to testing it

My configuration nginx on localhost like this :

location / {
    root   html;
    index  index.html index.htm;
}

If I refresh a page, it exist error like this :

404 Not Found
nginx/1.14.0 (Ubuntu)

I search on google and I get some reference. I try like this :

location / {
    root /www/dist;
    try_files $uri /index.html;
}

I works. There is no error

Then I deploy my project to production

My configuration nginx on production like this :

location / {
    root /www/dist;
    try_files $uri /index.html;
}

It works too

But my problem is I need to change the location to be like this :

location /startup {
    root /www/dist;
    try_files $uri /index.html;
}

I have a lot of projects in the nginx. So I have to add /startup to show that it's startup project. But it makes error like this :

404 Not Found
nginx/1.14.0 (Ubuntu)

How can I solve this problem?


Solution

  • When you use root in nginx, it always appends the route to the end of the file path but that's not obvious when using /. So in your first examples with location /, it searches for this path on the server:

    root + /www/dist + /
    

    But when you use location /startup, it looks for this path which does not exist:

    root + /www/dist + /startup
    

    So to use both root and "/startup", you would need a directory called "startup". But, you can use alias. Try this:

    location /startup {
        alias /www/dist;
        try_files $uri $uri/ /startup/index.html;
    }
    

    The Vue Router docs recommend something similar to this as well. (But they don't show how to use a subfolder alias.)