使用hash模式会有#,影响美观,所以使用history模式会是个更好的选择。
前端项目打包上线部署,可以使用下面的方式部署history模式的项目,下面以 jyH5 为例
expressjs部署
express脚手架搭建的app.js中添加如下代码:
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  const path = "/jyH5/";
  if (req.url.indexOf(path) !== -1) {//请求url包含 /jyH5/ 路径
    res.sendFile(__dirname + "/public" + path + "index.html"); // 返回 index.html 文件;
  }else{
    next(createError(404));
  }
});
app.use(express.static('public'))//暴露public文件夹下的所有文件打包后的文件放在 /public/jyH5/ 这个文件夹下,目录结构如下图:

koa2部署
koa2脚手架搭建的app.js中添加如下代码:
const fs = require("fs");
app.use(async (ctx, next) => { //使用 history 路由中间件,需要放在koa-static前执行
  const path = "/jyH5/"; // 项目部署的路径
  await next(); // 等待请求执行完毕
  console.log(ctx.request.url, ctx.response.status);
  if (ctx.response.status === 404 && ctx.request.url.includes(path)) {
    // 判断是否符合条件
    ctx.type = "text/html; charset=utf-8"; // 修改响应类型
    ctx.body = fs.readFileSync(__dirname + "/public" + path + "index.html"); // 修改响应体
  }
});
app.use(require('koa-static')(__dirname + '/public'))打包后的文件放在 /public/jyH5/ 这个文件夹下,目录结构如下图:

nginx部署
nginx.conf文件中添加如下代码:
http {
    #...其他配置
    server {
        listen       8080;
        server_name  localhost;
        # server_name  domain2.com www.domain2.com;
        
        # history路由模式需要下面的配置
        location / { #部署在根目录下
            index index.html index.htm;
            proxy_set_header Host $host;
            # history模式最重要就是这里
            try_files $uri $uri/ /index.html;
            # index.html文件设置协商缓存即可
            add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
        }
        location /jyH5 { #部署在根目录/jyH5文件夹下
            index /jyH5/index.html;
            proxy_set_header Host $host;
            # history模式最重要就是这里
            try_files $uri $uri/ /jyH5/index.html;#依次匹配try_files后面的所有地址,都没匹配上时使用最后一个地址
            # index.html文件设置协商缓存即可
            add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
        }
    }
}上面是两套配置,一套是部署在根目录下,一套是部署在jyH5目录下,根据自己需要配置。打包后的文件目录结构如下图:















![[Spring]Spring MVC 请求和响应及用到的注解](https://i-blog.csdnimg.cn/direct/a13a99e0108c413b80c0236565120887.png)


