当使用Nginx部署Vue项目时遇到找不到JS/CSS文件的问题,通常是由于路径配置不正确导致的。以下是常见原因和解决方案:
在vue.config.js
中确保publicPath设置正确:
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/' : '/',
// 或者如果你的项目部署在子目录下
// publicPath: '/sub-directory/'
}
server {
listen 80;
server_name yourdomain.com;
root /path/to/your/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存设置
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, no-transform";
}
}
server {
listen 80;
server_name yourdomain.com;
location /sub-directory/ {
alias /path/to/your/dist/;
index index.html;
try_files $uri $uri/ /sub-directory/index.html;
}
}
确保Nginx用户有权限访问静态文件:
chown -R www-data:www-data /path/to/your/dist
chmod -R 755 /path/to/your/dist
确保构建后的dist目录结构正确,通常应包含: - index.html - static/js/ - static/css/ - static/media/ (如果有图片等资源)
查看Nginx错误日志获取更多信息:
tail -f /var/log/nginx/error.log
try_files
通过以上步骤,应该能够解决Nginx部署Vue项目时找不到JS/CSS文件的问题。