IIS:URL Rewrite实现vue的地址重写

全局配置

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

URL Rewrite

1、添加规则

IIS:URL Rewrite实现vue的地址重写

2、设置规则

2.1.匹配url模式

这里选择与模式匹配、正则表达式

注意:

  1)这里匹配的URL是指URL的相对路径;比如: http://www.baidu.com/user/list?type=1;这里就URL对应是 usr/list?type=1

  2)模式就是正则表达式;

   例如:.* 就是匹配所有字符串;对应后续的重定向URL {R:0}

      ^api(/.*) 就是匹配URL后面api开头的后续路径;对应后续的重定向URL {R:1}

示例:

  1)实现:www.local.com的所有请求重定向到www.local2.com

    模式:.*   // 如 http://www.local.com/user/list?type=1 匹配到的就是user/list?type=1

    条件:{HTTP_HOST}  ^www.local.com$  // 这里是匹配地址

    操作:重定向、http://www.local.com/{R:0}

  2)实现:www.local.com/api下的所有请求转发到,api.local.com下; 如:http://www.local.com/api/user/list?type=1转发到http://api.local.com/user/list?type=1

    模式:^api(/.*)   // 如 http://www.local.com/api/user/list?type=1 这里{R:1}匹配到的就是 /user/list?type=1

    条件:{HTTP_HOST}  ^www.local.com$  // 这里是匹配地址

    操作:重写、http://api.local.com{R:1}    //注意,上面模式匹配带了斜杠 / 这里就不用带斜杠了

示例1)

IIS:URL Rewrite实现vue的地址重写

这里的{R:0}就是上面正则表达式匹配的内容:可以通过测试模式查看;也可以通过正则表达式的分组匹配去做跳转规则

IIS:URL Rewrite实现vue的地址重写

2)示例2

IIS:URL Rewrite实现vue的地址重写

IIS:URL Rewrite实现vue的地址重写

2.2条件详解与操作

条件可以设置服务器变量对应匹配,如上面只匹配www.local.com

服务器变量

https://docs.microsoft.com/en-us/previous-versions/iis/6.0-sdk/ms524602(v=vs.90)

IIS:URL Rewrite实现vue的地址重写

3、web.config

打开可以看到刚才的配置自动写入web.config的内容

    <system.webServer>
        <rewrite>
            <rules>
                <rule name="测试规则" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^www.local.com$" />
                    </conditions>
                    <action type="Redirect" url="http://www.asd.com/{R:0}" redirectType="Found" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>

IIS:URL Rewrite实现vue的地址重写

<system.webServer>
    <rewrite>
      <rules>
        <rule name="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>
404/500跳转首页