vue项目通过nginx部署在子目录

一、前言

最近写的vue项目,通过nginx部署,并且需要部署在nginx下的子目录,就是非html根目录。如果是部署在根目录,就比较简单了,但是部署在子目录,就踩了不少坑。

Linux安装Nginx详细教程可以看这篇:https://baijiahao.baidu.com/s?id=1659582871769773387&wfr=spider&for=pc

Nginx配置文件详解可以看这篇:https://www.cnblogs.com/hunttown/p/5759959.html

千万使用window版的Nginx去测试,很容易出现错误的。

二、配置

我们想要的效果是,比如域名是www.domain.com,我们的项目是配置在www.domain.com/admin 上,

1、vue项目的vue.config.js,publicPath设置为/admin/

module.exports = {
    publicPath: '/admin/',
    assetsDir: 'static',
    productionSourceMap: false,
}

2、router/index.js ,base设置为admin

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

export default new Router({
    mode: "history",
    base: "admin",
    routes: [...]
});

3、配置nginx.conf

 server {
      listen 8080;
      server_name localhost; 
      client_max_body_size 200m;
      location ~ \.(html|css|js|gif|jpg|jpeg|png|ttf|woff|ico|pdf|block|mp3)$ { 
           root html;
           index index.html index.htm; 
      }
      location / {
           root '/usr/local/nginx/html/admin'; 
           index index.html index.htm;
           try_files $uri $uri/ @router;
           add_header Cache-Control no-cache;
           add_header Access-Control-Allow-Origin *;
           add_header Access-Control-Allow-Credentials *;
           add_header Access-Control-Allow-Methods *;
           add_header Access-Control-Allow-Headers *;
      }
      location @router{
           rewrite ^.*$ /admin/index.html last;
      }
      error_page 500 502 503 504 /50x.html; 
      location = /50x.html {
           root html; 
      }
}

这里有个重点,我们的路径是存放在/usr/local/nginx/html/admin,意味着,我们要在html下创建admin文件夹,这个名称需要跟你想要的域名路径一致,例如www.domain.com/admin,不然是会请求不到的,将npm run build 生成的dist目录下的文件copy到admin目录去,遇到问题,可以看看nginx下logs,解决错误很有用的。

 

原文地址:https://www.cnblogs.com/cxt618/p/15672883.html