Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS Rules with React Router v4

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>
like image 553
Gabriel Avatar asked Dec 13 '22 21:12

Gabriel


2 Answers

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>
like image 78
Gabriel Avatar answered Jan 03 '23 16:01

Gabriel


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!

like image 29
Dave Cole Avatar answered Jan 03 '23 18:01

Dave Cole