简体   繁体   中英

nested route on react when serving with iis

I serve react SPA through IIS. (uploaded build results in specific directory)

Accessing url http://example.com/About directly or refresh returned 404 error, so I figured out to add web.config like below.

<?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" /> 
                        <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> 
                    </conditions> 
                    <action type="Rewrite" url="/" /> 
                </rule> 
            </rules> 
        </rewrite>
    </system.webServer> 
</configuration>

Previous problem is solved, but I still cannot access nested urls like http://example.com/directory/page1 directly. (Page does not return any error codes, just blank!)

Are there any missing points?

Thanks in advance.

I had the same problem and eventually realized that the web.config is good, but the problem were the relative paths to JS bundles in my index.html .

For example, a script tag in your index.html might be something like:

<script defer="defer" src="app.js"></script>

If you visit http://example.com/directory/page1 , IIS actually returns your index.html but the HTML contains relative src paths, so it tries to load the JS bundle at http://example.com/directory/app.js , which does not exist.

I fixed the issue by setting the output public path in my webpack config output: { publicPath: '/' } which makes the src an absolute path:

<script defer="defer" src="/app.js"></script>

https://webpack.js.org/configuration/output/#outputpublicpath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM