IIS Rules with React Router v4

与世无争的帅哥 提交于 2020-08-05 08:43:05

问题


I'm trying to get my routes to work with IIS and React Router v4 using BrowserRouter.

On my localhost I have all my routes working as expected. React Router handles everything like I want it to:

  • http://www.example.com/appfolder/dest
  • http://www.example.com/appfolder/dest/CODE
  • http://www.example.com/appfolder/dest/CODE/INVALID/URL

Now, in IIS I've set up a rule that ignores '/appfolder/api/*' for the purpose of serving an api for my app. That works.

How do I get IIS to redirect to 'http://www.example.com/appfolder/dest/CODE' and have React Router handle it according to its rules. If I redirect to '/appfolder/index.html' I loose my 'CODE' which I'd like to keep for ReactRouter to handle.

If I try to redirect to 'http://www.example.com/appfolder/dest/CODE' by using regexp capture groups, I get a 'ERR_TOO_MANY_REDIRECTS'.

I currently have this rule in my web.config:

    <rule name="ReactRouter Routes" stopProcessing="true">
      <match url=".*" />
      <conditions logicalGrouping="MatchAll">
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        <add input="{REQUEST_URI}" pattern="^/appfolder/api/" negate="true" />
      </conditions>
      <action type="Redirect" url="/appfolder/dest/CODE" />
      <!-- also tried this -->
      <!-- action type="Redirect" url="/appfolder/index.html" /-->
    </rule>

回答1:


I found the solution. I changed my action type to Rewrite and it worked like a charm.

IIS rule final solution:

<rule name="ReactRouter Routes" stopProcessing="true">
  <match url=".*" />
  <conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    <add input="{REQUEST_URI}" pattern="^/appfolder/api/" negate="true" />
  </conditions>
  <action type="Rewrite" url="/appfolder/index.html" />
</rule>



回答2:


The only way I was able to get things to work for me using react-router v4 was to use a HashRouter: https://reacttraining.com/react-router/web/api/HashRouter

No web.config changes required!



来源:https://stackoverflow.com/questions/45172640/iis-rules-with-react-router-v4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!