简介:本文详细讲解如何使用 Nginx 部署 Vue 项目,涵盖环境准备、Vue 构建、Nginx 配置、安全优化等全流程,适合前端开发者及运维人员。
在前端工程化日益成熟的今天,Vue.js 作为主流框架之一,其项目部署方案直接影响用户体验和系统稳定性。Nginx 以其高性能、轻量级和灵活的配置特性,成为部署静态资源的首选服务器。本文将通过手把手教学,详细讲解如何将 Vue 项目部署到 Nginx 服务器,涵盖环境准备、构建优化、配置文件编写、安全加固等全流程。
nginx -v 检查)
# Ubuntu/Debiansudo apt updatesudo apt install nginx# CentOS/RHELsudo yum install epel-releasesudo yum install nginx
验证安装:
sudo systemctl status nginx
在 vue.config.js 中设置 publicPath(关键步骤):
module.exports = {publicPath: process.env.NODE_ENV === 'production' ? '/your-subpath/' : '/',outputDir: 'dist', // 构建输出目录productionSourceMap: false // 生产环境关闭 source map}
npm run build
生成的文件结构:
dist/├── static/│ ├── css/│ ├── js/│ └── media/├── index.html└── favicon.ico
gzip_static 模块编辑 /etc/nginx/conf.d/vue-app.conf:
server {listen 80;server_name yourdomain.com;root /path/to/your-project/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";}}
try_files:解决 Vue Router 的 History 模式 404 问题root:必须指向构建后的 dist 目录
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com
sudo certbot renew --dry-run
upstream vue_app {server 127.0.0.1:3000;server 127.0.0.1:3001;}server {location / {proxy_pass http://vue_app;proxy_set_header Host $host;}}
dist 目录:
scp -r dist/ user@server:/path/to/project
sudo nginx -t # 测试配置sudo systemctl restart nginx
创建 .deploy/deploy.sh:
#!/bin/bashnpm run buildrsync -avz --delete dist/ user@server:/path/to/projectssh user@server "sudo systemctl restart nginx"
Dockerfile 内容:
FROM nginx:alpineCOPY dist/ /usr/share/nginx/htmlCOPY nginx.conf /etc/nginx/conf.d/default.conf
构建并运行:
docker build -t vue-app .docker run -d -p 80:80 vue-app
原因:未正确配置 try_files
解决:确保 location 块包含 try_files $uri $uri/ /index.html;
检查项:
publicPath 是否与服务器路径匹配root 路径是否正确在 Nginx 中添加:
location /api/ {proxy_pass http://backend-server;proxy_set_header Host $host;add_header 'Access-Control-Allow-Origin' '*';}
修改 nginx.conf:
listen 443 ssl http2;ssl_protocols TLSv1.2 TLSv1.3;
location ~* \.(js|css)$ {expires 1y;add_header Cache-Control "public";}location / {add_header Cache-Control "no-store";}
配置访问日志:
log_format vue_app '$remote_addr - $request_time - $upstream_response_time';access_log /var/log/nginx/vue-app.access.log vue_app;
# 禁用敏感信息泄露server_tokens off;# 限制请求方法if ($request_method !~ ^(GET|HEAD|POST)$ ) {return 444;}
sudo apt install libnginx-mod-http-modsecurity
sudo apt upgrade nginx
production 模式nginx -t 测试通过本文的手把手指导,您已掌握从 Vue 项目构建到 Nginx 部署的全流程。实际部署中,建议先在测试环境验证配置,再逐步推广到生产环境。遇到问题时,可结合 Nginx 错误日志(/var/log/nginx/error.log)和浏览器开发者工具进行排查。