手把手教Nginx部署Vue项目:从构建到上线的完整指南

一、环境准备与项目构建

1.1 开发环境要求

部署前需确保服务器环境满足以下条件:

  • 操作系统:Linux(推荐Ubuntu/CentOS)或Windows Server(需配置Nginx)
  • Nginx版本:1.18.0+(支持HTTP/2和动态模块)
  • Node.js环境:LTS版本(用于构建Vue项目)
  • 网络要求:开放80(HTTP)和443(HTTPS)端口

1.2 Vue项目构建优化

vue.config.js中配置生产环境参数:

  1. module.exports = {
  2. publicPath: process.env.NODE_ENV === 'production'
  3. ? '/your-project-name/' // 部署到子目录时设置
  4. : '/',
  5. outputDir: 'dist',
  6. productionSourceMap: false, // 关闭source map减少体积
  7. configureWebpack: {
  8. performance: {
  9. hints: false // 关闭大文件警告
  10. }
  11. }
  12. }

执行构建命令:

  1. npm run build

生成的文件结构应包含:

  1. dist/
  2. ├── static/
  3. ├── css/
  4. ├── js/
  5. └── media/
  6. ├── index.html
  7. └── favicon.ico

二、Nginx基础配置

2.1 安装Nginx

Ubuntu示例

  1. sudo apt update
  2. sudo apt install nginx -y
  3. sudo systemctl start nginx
  4. sudo systemctl enable nginx

验证安装:

  1. curl -I localhost
  2. # 应返回HTTP/1.1 200 OK

2.2 基础配置文件

创建配置文件/etc/nginx/conf.d/vue-app.conf

  1. server {
  2. listen 80;
  3. server_name your-domain.com;
  4. root /var/www/vue-app/dist;
  5. index index.html;
  6. location / {
  7. try_files $uri $uri/ /index.html;
  8. }
  9. # 静态资源缓存配置
  10. location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
  11. expires 1y;
  12. add_header Cache-Control "public, no-transform";
  13. }
  14. }

关键配置说明:

  • try_files:确保Vue路由在刷新时能正确返回index.html
  • expires:设置静态资源缓存时间
  • add_header:防止CDN缓存转换(如WebP转换)

三、高级部署场景

3.1 部署到子目录

修改配置支持路径前缀:

  1. server {
  2. listen 80;
  3. server_name your-domain.com;
  4. location /subpath/ {
  5. alias /var/www/vue-app/dist/;
  6. try_files $uri $uri/ /subpath/index.html;
  7. }
  8. }

同时需在vue.config.js中设置:

  1. publicPath: '/subpath/'

3.2 HTTPS配置(Let’s Encrypt)

安装Certbot:

  1. sudo apt install certbot python3-certbot-nginx -y

获取证书:

  1. sudo certbot --nginx -d your-domain.com

自动生成的配置示例:

  1. server {
  2. listen 443 ssl;
  3. server_name your-domain.com;
  4. ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem;
  5. ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem;
  6. # 安全增强配置
  7. ssl_protocols TLSv1.2 TLSv1.3;
  8. ssl_ciphers HIGH:!aNULL:!MD5;
  9. ssl_prefer_server_ciphers on;
  10. # HTTP到HTTPS重定向
  11. location / {
  12. return 301 https://$host$request_uri;
  13. }
  14. }

四、性能优化与监控

4.1 Gzip压缩配置

nginx.conf的http块中添加:

  1. gzip on;
  2. gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
  3. gzip_min_length 1024;
  4. gzip_comp_level 6;

4.2 负载均衡配置(多实例部署)

  1. upstream vue_app {
  2. server 127.0.0.1:8080 weight=3;
  3. server 127.0.0.1:8081;
  4. server 127.0.0.1:8082 backup;
  5. }
  6. server {
  7. listen 80;
  8. location / {
  9. proxy_pass http://vue_app;
  10. proxy_set_header Host $host;
  11. proxy_set_header X-Real-IP $remote_addr;
  12. }
  13. }

4.3 日志监控

配置访问日志和错误日志:

  1. server {
  2. access_log /var/log/nginx/vue-app.access.log;
  3. error_log /var/log/nginx/vue-app.error.log warn;
  4. # 日志格式示例
  5. log_format vue_app_format '$remote_addr - $remote_user [$time_local] '
  6. '"$request" $status $body_bytes_sent '
  7. '"$http_referer" "$http_user_agent" "$request_time"';
  8. }

五、常见问题解决方案

5.1 路由404问题

现象:直接访问子路由返回404
解决方案:确保Nginx配置包含:

  1. location / {
  2. try_files $uri $uri/ /index.html;
  3. }

5.2 静态资源加载失败

检查项

  1. 确认publicPath配置正确
  2. 检查Nginx的rootalias路径
  3. 使用开发者工具查看网络请求是否404

5.3 跨域问题(API请求)

配置CORS头:

  1. location /api/ {
  2. add_header 'Access-Control-Allow-Origin' '*';
  3. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  4. proxy_pass http://backend-server;
  5. }

六、自动化部署方案

6.1 Git Hook自动部署

创建.git/hooks/post-receive

  1. #!/bin/bash
  2. TARGET="/var/www/vue-app"
  3. GIT_DIR="/path/to/repo.git"
  4. BRANCH="master"
  5. while read oldrev newrev ref
  6. do
  7. if [[ $ref = refs/heads/$BRANCH ]];
  8. then
  9. echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
  10. git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH
  11. cd $TARGET
  12. npm install --production
  13. npm run build
  14. systemctl reload nginx
  15. else
  16. echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
  17. fi
  18. done

6.2 Docker容器化部署

Dockerfile示例:

  1. FROM nginx:alpine
  2. COPY dist/ /usr/share/nginx/html
  3. COPY nginx.conf /etc/nginx/conf.d/default.conf
  4. EXPOSE 80
  5. CMD ["nginx", "-g", "daemon off;"]

构建并运行:

  1. docker build -t vue-app .
  2. docker run -d -p 8080:80 --name vue-container vue-app

七、安全加固建议

  1. 禁用敏感目录访问
    1. location ~ /\.ht {
    2. deny all;
    3. }
  2. 限制请求速率
    1. limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
    2. server {
    3. location / {
    4. limit_req zone=one burst=20;
    5. }
    6. }
  3. 定期更新Nginx
    1. sudo apt update && sudo apt upgrade nginx -y

通过以上完整流程,开发者可以系统掌握从本地构建到生产环境部署的全链路操作。实际部署时建议先在测试环境验证配置,再逐步迁移到生产环境。对于高流量项目,建议结合CDN加速和自动扩缩容机制实现更稳定的运行。