插件窝 干货文章 Windows系统下如何使用nginx部署vue2项目

Windows系统下如何使用nginx部署vue2项目

Nginx 配置 html 部署 322    来源:    2025-04-24

在Windows系统下使用Nginx部署Vue2项目

准备工作

  1. 确保你已经完成Vue2项目的开发并进行了生产环境构建
  2. 下载Windows版Nginx:官网下载

部署步骤

1. 构建Vue2项目

npm run build

这会在项目目录下生成一个dist文件夹,包含所有静态文件。

2. 安装和配置Nginx

  1. 解压下载的Nginx压缩包到任意目录(例如C:\nginx
  2. 打开conf/nginx.conf文件进行配置

3. 配置Nginx

修改nginx.conf文件中的server部分:

server {
    listen       80;
    server_name  localhost;  # 可以改为你的域名或IP

    location / {
        root   html;  # 这里可以改为你的dist文件夹路径
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;  # 处理Vue路由的history模式
    }

    # 可选:配置API代理
    location /api/ {
        proxy_pass http://your-api-server.com;  # 你的后端API地址
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}

4. 部署Vue项目

将Vue项目的dist文件夹内容复制到Nginx的html目录下(默认是nginx-1.x.x/html),或者修改root指令指向你的dist文件夹路径。

5. 启动Nginx

在Nginx目录下:

start nginx

6. 验证部署

打开浏览器访问http://localhost,应该能看到你的Vue应用。

常用Nginx命令

  • 启动Nginx:start nginx
  • 重新加载配置:nginx -s reload
  • 停止Nginx:nginx -s stop
  • 快速停止:nginx -s quit

注意事项

  1. 路由模式:如果使用history模式,确保Nginx配置中包含try_files $uri $uri/ /index.html;
  2. 端口冲突:如果80端口被占用,可以修改listen指令使用其他端口
  3. 跨域问题:如果需要访问后端API,建议在Nginx中配置反向代理
  4. 静态资源路径:确保Vue项目中config/index.jsassetsPublicPath正确(通常为/./

高级配置(可选)

启用Gzip压缩

gzip on;
gzip_min_length 1k;
gzip_comp_level 2;
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
gzip_vary on;

配置HTTPS

  1. 获取SSL证书
  2. 修改Nginx配置:
server {
    listen       443 ssl;
    server_name  yourdomain.com;

    ssl_certificate      cert.pem;
    ssl_certificate_key  cert.key;

    # 其他配置...
}

通过以上步骤,你就可以在Windows系统下成功使用Nginx部署Vue2项目了。