vue部署后,访问路径问题

问题:

访问 https://zkaim.com/ocms/ 正常
访问 https://zkaim.com/ocms 就报404

已知vue2.5.9:

nginx配置如下

location /ocms/ {
            root /home;
            #index  index.html index.htm;
        }

vue路由配置如下

mode: 'history',
base: '/ocms/'
...

以及config配置中的assetsPublicPath跟base相同

阅读 8k
3 个回答

因为你的nginx配置是location /ocms/
这样是无法匹配到/ocms请求的
建议配置改为

location /ocms {
    root /home;
    try_files $uri $uri/;
    #index  index.html index.htm;
}

今天刚回答了一个类似的问题,我就直接把答案粘贴过来了!
单页面应用应该放到nginx或者apache、tomcat等web代理服务器中,同时要根据自己服务器的项目路径更改vue的路由地址。
如果说项目是直接跟在域名后面的,比如:http://www.sosout.com ,根路由就是 '/'。
如果说项目是直接跟在域名后面的一个子目录中的,比如:http://www.sosout.com/children ,根路由就是 '/children ',不能直接访问index.html。

以配置Nginx为例,配置过程大致如下:
(假设:1、项目文件目录: /mnt/html/vueCli(vueCli目录下的文件就是执行了打包后生成的目标目录下的文件);2、访问域名:vue.sosout.com)

进入nginx.conf新增如下配置:

server {
    listen 80;
    server_name vue.sosout.com;
    root /mnt/html/vueCli;
    index index.html;
    location ~ ^/favicon.ico$ {
        root /mnt/html/vueCli;
    }

    location / {
        try_files $uri $uri/ /index.html;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto  $scheme;
    }
    access_log  /mnt/logs/nginx/access.log  main;
}

注意事项:
1、配置域名的话,需要80端口,成功后,只要访问域名即可访问的项目
2、如果你使用了vue-router的history模式,在nginx配置还需要重写路由:

server {
    listen 80;
    server_name vue.sosout.com;
    root /mnt/html/vueCli;
    index index.html;
    location ~ ^/favicon.ico$ {
        root /mnt/html/vueCli;
    }
    
    location / {
        try_files $uri $uri/ @fallback;
        index index.html;
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto  $scheme;
    }
    location @fallback {
        rewrite ^.*$ /index.html break;
    }
    access_log  /mnt/logs/nginx/access.log  main;
}

为什么要重写路由?
因为我们的项目只有一个根入口,当输入类似/home的url时,如果找不到对应的页面,nginx会尝试加载index.html,这是通过vue-router就能正确的匹配我们输入的/home路由,从而显示正确的home页面,如果history模式的项目没有配置上述内容,会出现404的情况。

原问题链接:https://segmentfault.com/q/10...

base: '/ocms'试试?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题