Bootstrap

Vue/React单页面应用部署到nginx服务器时,错误解决以及刷新404

2024/10/29 11:53:08 [crit] 1543223#1543223: *8311 stat() "/home/songjj/crmI18n/dist/" failed (13: Permission denied), client: 139.226.64.118, server: _, request: "GET / HTTP/1.1", host: "47.253.55.217:8081"
2024/10/29 11:53:08 [crit] 1543223#1543223: *8311 stat() "/home/songjj/crmI18n/dist/" failed (13: Permission denied), client: 139.226.64.118, server: _, request: "GET / HTTP/1.1", host: "47.253.55.217:8081"
2024/10/29 11:53:08 [crit] 1543223#1543223: *8311 stat() "/home/songjj/crmI18n/dist/favicon.ico" failed (13: Permission denied), client: 139.226.64.118, server: _, request: "GET /favicon.ico HTTP/1.1", host: "47.253.55.217:8081", referrer: "http://47.253.55.217:8081/"
2024/10/29 11:53:08 [crit] 1543223#1543223: *8311 stat() "/home/songjj/crmI18n/dist/favicon.ico" failed (13: Permission denied), client: 139.226.64.118, server: _, request: "GET /favicon.ico HTTP/1.1", host: "47.253.55.217:8081", referrer: "http://47.253.55.217:8081/"
2024/10/29 11:53:31 [notice] 1544206#1544206: signal process started
2024/10/29 13:31:36 [crit] 1544207#1544207: *8322 stat() "/home/songjj/crmI18n/dist/" failed (13: Permission denied), client: 139.226.64.118, server: _, request: "GET / HTTP/1.1", host: "47.253.55.217:8081"
2024/10/29 13:31:36 [crit] 1544207#1544207: *8322 stat() "/home/songjj/crmI18n/dist/" failed (13: Permission denied), client: 139.226.64.118, server: _, request: "GET / HTTP/1.1", host: "47.253.55.217:8081"
 

1.Permission denied问题原因:

可能是没有将dist文件夹放置到var/www/目录中,因为Permission denied 错误通常是因为 Nginx 进程对 /home/xxxx/crmI18n/dist/ 目录没有足够的权限。但是对var/www目录是有访问权限的。

解决办法:

将项目部署到var/www目录中,然后修改nginx里面的root路径地址为var/www中

2.直接访问首页可以,但是跳转到登录页面等刷新之后就404了

解决办法:

这个问题可能是由于单页面应用 (SPA) 的路由配置导致的。一般来说,SPA 通过前端路由来管理页面导航,而刷新页面时,Nginx 直接尝试加载当前 URL 的资源,却找不到对应的文件,从而导致 404 错误。

可以通过配置 Nginx 将所有请求都重定向到 index.html,让前端的路由逻辑来处理 URL。以下是具体解决方案:

修改 Nginx 配置以支持 SPA 路由

将 Nginx 配置修改为以下内容,以确保所有请求都可以重定向到 index.html

server {
    listen 8081;
    server_name _;

    root /var/www/crmI18n;

    location / {
        try_files $uri $uri/ /index.html;
    }

    # 静态资源直接访问
    location /assets/ {
        try_files $uri $uri/ =404;
    }
}

解释配置

try_files $uri $uri/ /index.html; 这条指令会尝试按顺序查找请求的资源,首先查找 $uri,即用户请求的资源。如果找不到,再查找 $uri/,即资源文件夹。如果仍然找不到,则将请求重定向到 /index.html,由前端来处理路由。

更新 Nginx 配置

修改完 Nginx 配置后,执行以下命令重新加载配置:

sudo nginx -s reload 

这样,当用户在登录页面或其他页面刷新时,Nginx 会将请求重定向到 index.html,前端应用可以解析 URL 并渲染对应的页面内容。

;