When hosting a React app with React Router on an IIS (Internet Information Services) server, routing issues often occur because IIS handles routes differently than typical single-page application servers. This guide walks you through configuring IIS rewrite rules, setting up React Router correctly, and troubleshooting common deployment problems to ensure your client-side routing works seamlessly on IIS.
How to Configure React Router on IIS
-
Step 1: Configure IIS Rewrite Rules
IIS needs to be configured to properly handle client-side routing. Add rewrite rules to your
web.configfile to redirect all requests to theindex.htmlfile:<configuration> <system.webServer> <rewrite> <rules> <rule name="React Router 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="/" /> </rule> </rules> </rewrite> </system.webServer> </configuration>Place this configuration inside your
web.configfile in the root directory of your React app. -
Step 2: Set basename Prop in React Router
In your React Router configuration, use the
basenameprop to specify the base URL for all locations. This should match the subdirectory or virtual directory where your app is hosted on the IIS server:<BrowserRouter basename="/your-subdirectory"> {/* Routes */} </BrowserRouter>Replace
/your-subdirectorywith the actual subdirectory path where your app is hosted on the server. -
Step 3: Configure Build Settings
When building your React app, configure the correct homepage URL in your
package.jsonfile. This should also match the subdirectory or virtual directory where your app will be hosted on the IIS server:"homepage": "/your-subdirectory"Replace
/your-subdirectorywith the actual subdirectory path. -
Step 4: Test Locally
Before deploying to the IIS server, test your React app locally to ensure that routing works as expected. You can use tools like
serveorhttp-serverto serve your built React app locally and test routing. -
Step 5: Deploy and Debug
Deploy your React app to the IIS server and test routing. If you encounter any issues, use browser developer tools to inspect network requests and console errors for clues about what might be going wrong.