关于iis部署vue项目到子目录(history模式)

973 阅读1分钟

概述

vue默认模式是hash模式    url地址栏会带有“#”这个字符。例如:http://www.ebux.cn/#/index , 感觉和正常的url相比有点丑。因此我们如果想要解决去掉#,就需要配置history模式,需要服务端支持,通常情况下,我们前端项目打包之后都是直接部署到服务器的根目录下面,但是有时候,需要在服务器子目录下面部署项目,并且还要通过前端history模式刷新不能500或者404,因此我们需要额外配置。配置分为前端和服务端的配置。

前端(vue项目举例)

vue.config.js
modules.exports={
      publicPath: '/h5/',
}
  • 其次,修改router配置项的base字段
const router = new VueRouter({
  routes,
  mode: 'history',
  base: '/h5/',
});

  • 新建web.config文件,添加如下配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
        //rules表示匹配规则组,rule项从前面匹配,匹配到就不会看后面的rule
      <rules>
      //表示项目文件的匹配规则
          <rule name="Handle History h5 and custom 404/500" stopProcessing="true">
          //正则:下面匹配的就是路径为h5/xxx的子目录
                    <match url="^h5\/(.*)" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="/h5/" />
                </rule>
                //由于只配置了一个子目录,因此,其他的直接匹配到跟目录的index.html就行了
        <rule name="Handle  History Mode and custom 404/500" stopProcessing="true">
                  <match url="(.*)" />
                  <conditions logicalGrouping="MatchAll">
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                  </conditions>
                  <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>
  • 最后将web.config文件放到服务器项目部署文件夹的根目录下,就OK了

image.png

image.png

  • 总结 网上搜到的资料多数是解决根目录下面history模式访问的解决方案,关于嵌套子项目的history解决方案比较难找,这里记录下。