我开发了一个 Vue 项目,在本地运行 npm run serve 时,页面中的图片都能正常显示。但将项目打包部署到服务器(CentOS 7 系统,使用 Nginx 作为 Web 服务器)后,图片却显示不出来,页面上只显示图片的占位符。
我的 Vue 项目结构大致如下:
my-vue-project/
│
├── public/
│ ├── index.html
│ └── favicon.ico
│
├── src/
│ ├── assets/
│ │ ├── img/
│ │ │ ├── logo.png
│ │ │ └── bg.jpg
│ │ └── style.css
│ ├── components/
│ │ ├── MyComponent.vue
│ │ └──...
│ ├── main.js
│ └── App.vue
│
├── package.json
└──...
在 MyComponent.vue 中引用图片的代码如下:
<template>
<div>
<img src="@/assets/img/logo.png" alt="logo">
</div>
</template>
在本地开发环境中,图片路径 @/assets/img/logo.png 能正确解析并显示图片。打包部署到服务器后,Nginx 配置如下:
server {
listen 80;
server_name myserver.com;
root /path/to/my-vue-project/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
请问怎样才能让图片在服务器上正常显示呢?
尝试过的解决方案
检查图片路径:
确认在服务器上项目的dist目录下,图片文件确实存在于对应的路径中,通过ls命令查看无误。
检查 Vue 项目中图片引用路径,在打包后的index.html文件中,图片路径看起来是相对正确的,类似/assets/img/logo.png。
检查 Nginx 配置:
仔细检查 Nginx 配置文件,确保root指令指向了正确的项目dist目录。尝试修改try_files指令的参数顺序,问题依旧。
使用sudo nginx -t检查 Nginx 配置语法,无报错,然后用sudo systemctl reload nginx重新加载配置。
清除浏览器缓存:
在浏览器中多次清除缓存,包括强制刷新页面(Ctrl + F5),但图片仍无法显示。
检查文件权限:
确保服务器上项目目录及其所有文件权限设置正确,使用chmod -R 755 /path/to/my-vue-project/dist赋予了适当权限。
这个是我自己项目的配置,改下root试试