使用nginx部署vue项目
通常有两种部署方式,根目录部署和二级目录部署。下面以若依管理系统为例,分别介绍这两种部署方式。
🍎根目录部署
这是比较常用的一种方式,部署后一般通过ip+端口访问,例如http://localhost:8080。
这种方式通常不需要额外的配置,只需要打包项目后放到服务器上,并参照如下nginx配置即可。
server {
listen 8080;
server_name localhost;
location / {
# 将path/web/替换为实际路径
root path/web/;
index index.html;
try_files $uri $uri/ /index.html;
}
# 后端服务
location /prod-api/ {
proxy_pass http://localhost:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
🍍二级目录部署
这种部署方式相较于根目录部署,访问时多了一层目录,例如http://localhost:8080/admin。主要适用于多项目部署到同一端口下的场景。
代码配置
vue2版本
- 在
.env.development中添加VUE_APP_PUBLIC_PATH = / - 在
.env.production中添加VUE_APP_PUBLIC_PATH = /admin/,注意前后都要有/ 修改
vue.config.jsmodule.exports = { publicPath: process.env.VUE_APP_PUBLIC_PATH, }修改
router/index.jsexport default new Router({ base: process.env.VUE_APP_PUBLIC_PATH, mode: 'history', scrollBehavior: () => ({ y: 0 }), routes: constantRoutes })
- 在
vue3版本
- 在
.env.development中添加VITE_APP_PUBLIC_PATH = / - 在
.env.production中添加VITE_APP_PUBLIC_PATH = /admin/,注意前后都要有/ 修改
vite.config.js... export default defineConfig(({ mode, command }) => { const env = loadEnv(mode, process.cwd()) const { VITE_APP_ENV, VITE_APP_PUBLIC_PATH } = env return { base: VITE_APP_PUBLIC_PATH, ... } })修改
router/index.jsconst router = createRouter({ history: createWebHistory(import.meta.env.VITE_APP_PUBLIC_PATH), ... })
- 在
nginx配置server { listen 8080; server_name localhost; # '/admin/'也可以换成其他,如'/app/'等,只要与代码中的配置保持一致即可 location /admin/ { # 将path/web/替换为实际路径(注意这里使用的是alias,而不是root) alias path/web/; index index.html; # index.html前添加的前缀,与location的'/admin/'保持一致 try_files $uri $uri/ /admin/index.html; } # 重定向/admin到/admin/ location = /admin { return 302 /admin/; } # 后端服务 location /prod-api/ { proxy_pass http://localhost:3000/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }