Home > Software design >  React and IIS rewrite url configuration
React and IIS rewrite url configuration

Time:03-11

I have a problem about "React route" and "IIS confiugration". I added in the IIS the following url rewrite role:

<?xml version="1.0" encoding="UTF-8"?>    
<configuration>    
 <system.webServer>    
   <rewrite>    
     <rules>    
       <rule name="React Routes" 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="/index.html" />    
       </rule>    
     </rules>    
   </rewrite>
        <httpProtocol>
            <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
            </customHeaders>
        </httpProtocol>    
 </system.webServer>    
</configuration> 

With that configuration when I navigate using the app it works fine, but if i try to refresh the page, it become Blank, it's seems the url rewrite doesen't work. (that's do not happen if i try use a node server)

CodePudding user response:

It looks like your url rewrite rule configuration is correct, I think the problem should be that React route is not processing the url, if the index page does not send the request to the react route, this will cause the problem.

In this case, you can try adding to the Index.html page, this should solve your problem. And the href attribute should be adjusted according to your react app.

You could also refer to this similar case: How do I setup react-router clean URL's with IIS?

CodePudding user response:

Thank's @Xudong Peng for the suggestion, that's help me to resolve the issue.

The problem was about the path of the script tags, The urls of the file are setted as relative path and not as absolute path:

<script defer="defer" src="main.bundle.js">

instead of:

<script defer="defer" src="/main.bundle.js">

That's was given by a missing configuration of webpack, I do not set the publicPath in the output node

output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        publicPath: '/',
        clean: true,
    }

Adding that the problem will be solved.

  • Related