Search code examples
node.jsreactjsiisiis-10

How to set up ReactJS app on IIS properly?


Watched through few topics on same question. None worked for me. The thing is: I have ReactJS + Redux app designed from create-react-app. Actually it works but when app surfing starts with URL different from root is throws out 404. Installed iisnode and tried out different rewrite rules recommended in web, but nothing works. Last was this one:

    <rule name="Redirect HTTP to HTTPS">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent"/>
    </rule> -->

    <rule name="Redirect non-existent paths to root">
      <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="^/initialLogin/*" ignoreCase="true" negate="true" />            
      </conditions>
      <action type="Redirect" url="/" appendQueryString="false" />
    </rule>
  </rules>
</rewrite>

The only thing I need is to send all incoming requests through root url with passing the rest of the address to it so that SPA could work properly. Hosting: AzureVM IIS: v10

Edit: Another curious thing is thet iisnode can handle redirections with js files, but my application renders in index.html and when I tried to point index.html as handler it actually showed me a blank page.


Solution

  • This web.config works for me. Hope it will help someone else.

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
        <system.webServer>
            <!-- This part is responsible for URL rewrites -->
            <rewrite>
              <rules>
                <rule name="ReactJS 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="^/(api)" negate="true" />
                  </conditions>
                  <action type="Rewrite" url="/" />
                </rule>
              </rules>
            </rewrite>
            <!-- This allows CORS for testing purposes -->
            <httpProtocol>
             <customHeaders>
               <add name="Access-Control-Allow-Origin" value="*" />
             </customHeaders>
           </httpProtocol>
      </system.webServer>
    </configuration>