如何让 IIS 支持 vue 多页面路由
现在流行的前端框架比如
vue
,
react
都是采用单页面开发,例如一个真实的文件地址和若干个虚拟的路由地址组成,如果使用
hash
访问除了丑一点外省了配置的功夫,但就是太丑了所以很多人会用
history
模式,不过造成的问题就是打包后部署刷新就会出现
404
从HTML5开始,History interface提供了两个新的方法:pushState(), replaceState()使得我们可以对浏览器历史记录栈进行修改当调用他们修改浏览器历史记录栈后,
虽然当前URL改变了,但浏览器不会立即发送请求该URL
( the browser won’t attempt to load this URL after a call to pushState() )
具体原理可以移步下面这篇文章从vue-router看前端路由的两种实现
配置
关于下载的步骤流程之前有篇文章已经写过了,这里就不再重复
点击添加规则
最后可以看到如下界面,
Requested URL
选择 matches the pattern
Using
这里选择正则表达式
pattern
写正则,从/
后开始匹配,当时这里卡了我好几个小时,硬是匹配不上,后面发现 a.com/open/login
其实是从 open/login
开始匹配的,比如我这段正则就是匹配 open
开头的所有地址
logical grouping
这里选择match All
因为我们匹配的不是个文件和文件夹
最后在Action
里选择Rewrite
,在Rewrite url
中填入要跳转的login.html
,这样子所有访问open
开头的都会跳转到login.html
最后web.config
生成的规则如下,有3个主页面,一个是登陆open
登陆页,account
登陆后查看的页面,404
无需登陆的页面。也可以新建.htaccess
直接导入,配置文件也会自动更新
<rule name="open" stopProcessing="true">
<match url="(open\/.*)"/>
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="login.html" />
</rule>
<rule name="account" stopProcessing="true">
<match url="(account\/.*)"/>
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="account.html" />
</rule>
<rule name="404" 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>
拓展
官方文档
详解IIS中URL重写工具的规则条件(Rule conditions)
详解IIS中URL重写工具的匹配URL-规则模式(rule patterns)
详解IIS中的重写工具下关于操作重定向URL中的{R:N}与{C:N}