nginx部署vue前端,增加项目访问前缀
通常我们nginx部署前端只需要默认的端口访问如: http://127.0.0.1:8080,
但是有时候多个项目部署在一个地址上,我们需要通过前缀来区分,例如http://127.0.0.1:8080/test1, http://127.0.0.1/test2.
此时就需要非常规配置. 此处我们演示的是docker环境下的nginx配置.docker的nginx配置可以参考nginx部署 ( docker )
vue项目的vu.config.js配置, 注意publicPath
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| module.exports = { publicPath: '/', assetsDir: 'static', outputDir: 'dist', chainWebpack: config => { config.resolve.alias.set('@', resolve('src')) }, configureWebpack: { devtool: 'source-map' }, devServer: { open: true, host: '0.0.0.0', port: 8080, proxy: { [process.env.VUE_APP_BASE_API]: { target: process.env.VUE_APP_URL, changeOrigin: true, pathRewrite: { ['^' + process.env.VUE_APP_BASE_API]: '' } } } } }
|
nginx的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| listen 8080; server_name 127.0.0.1; index index.html index.htm;
location / { # 此处为挂载目录的指定项目文件夹 root /usr/share/nginx/html/test; try_files $uri $uri/ /index.html; index index.html index.htm; } # 代理后端接口 location /api/{ proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 后端接口地址 proxy_pass http://127.0.0.1:9999/; }
|
vue项目的vu.config.js配置, 注意publicPath
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| module.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/test/' : '/', assetsDir: 'static', outputDir: 'dist', chainWebpack: config => { config.resolve.alias.set('@', resolve('src')).set('api', resolve('service/api')) }, configureWebpack: { devtool: 'source-map' }, devServer: { open: true, host: '0.0.0.0', port: 8080, proxy: { [process.env.VUE_APP_BASE_API]: { target: process.env.VUE_APP_URL, changeOrigin: true, pathRewrite: { ['^' + process.env.VUE_APP_BASE_API]: '' } } } } }
|
router/index.js配置
vue2
1 2 3 4 5 6
| const router = new VueRouter({ mode: 'history', base: process.env.NODE_ENV === 'production' ? '/test/' : '/', routes, })
|
vue3
1 2 3 4 5
| const base = process.env.NODE_ENV === 'production' ? '/test/' : '/' const router = createRouter({ history: createWebHashHistory(base), routes, })
|
nginx配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| server { listen 8080; server_name 127.0.0.1; index index.html index.htm; location / { root html; try_files $uri $uri/ /index.html; index index.html index.htm; }
location /test { # 这里要用别名天写项目包路径 alias /usr/share/nginx/html/test/; # 此处是 前缀/index.html try_files $uri $uri/ /test/index.html; index index.html index.htm; } location /api/{ proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:9999/; } }
|