The nginx service refreshes the page after deploying the Vue project, and there is a 404 problem

Time:2021-1-15

Environmental Science

1.vue-cli 3.x
2.Nginx

overview

Before the project, Vue router used the default "hash" mode, which is no problem in the local and online environment. Because the "#" in the URL is removed, the "history" routing mode is used. After the online environment is deployed again, the home page can be accessed normally, and there is no problem in clicking switch in the menu. However, when you refresh the page, 404 Not will appear So here's the solution

Solutions

When the page is refreshed, the resource to be accessed can not be found on the server, because the routing address set by Vue router is regarded as the URL address, and the address path certainly does not exist, so 404 phenomenon appears.

The nginx service refreshes the page after deploying the Vue project, and there is a 404 problem

The reason for the above phenomenon is that there is no real resource 'menu / index' under the root directory / www / wwwroot / ssoshuang / dist of nginx configuration. These access resources are rendered in JS.
The initial configuration of nginx on the server is as follows (assuming the domain name is: testwx.wangshibo.com ):
server
{
    listen 80;
    server_name testwx.wangshibo.com;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/ssoShuang/dist;
}
The reason why 404 appears above is that there is no real directory 'menu / index' under the root directory of the domain name / www / wwwroot / ssoshuang / dist.

solve the problem

Add the jump setting of Vue route in the nginx configuration of the server (the first page here is index.html , if yes index.php The correct configuration is as follows:
server
{
    listen 80;
    server_name testwx.wangshibo.com;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/ssoShuang/dist;

    #Vue router configuration
    location / {
        try_files $uri $uri/ @router;
        index index.html;
    }
    location @router {
        rewrite ^.*$ /index.html last;
    }
}

After restarting nginx, the problem is solved.

This work adoptsCC agreementReprint must indicate the author and the link of this article