React Router – Handling Page Refresh on the Server

Overview
When deploying to a server, you may notice the router doesn’t work properly if you reload the page. Here are a couple of solutions.
LINUX
Create or Update the .htaccess file to sit at the root of the application with the following.
Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
To force a redirect to HTTPS add the following in addition to the above.
# Redirect to HTTPS
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://csjobsearch.com/$1 [R,L]
Windows IIS
If your React application is in a subfolder with the API at the root you can use the API’s web.config and add a custom error for 404. In the example below the subfolder is labeled “/app”;
<customErrors mode="On">
<error statusCode="404" redirect="/app" />
</customErrors>
The section would fall in between the <system.web> tag.
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="/app" />
</customErrors>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
OR
Or use the <rewrite> <rules> tags to handle page reloads.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Static Files" stopProcessing="true">
<match url="([\S]+[.](html|htm|svg|js|css|png|gif|jpg|jpeg))" />
<action type="Rewrite" url="/{R:1}"/>
</rule>
<rule name="React Router" 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>
</system.webServer>
</configuration>
IIS Server Admin
If the React Application is at the root then open the IIS Errors

Update the custom 404 page to redirect to the root and then handle the refresh.

Azure
How to override the 404 Page Not Found Error
Open Web.config at the root of your ASP.NET App if the Client and API are on the same site.
Add the following to the <system.web> and <system.webServer> sections.
The example below has a root folder labeled “/app” for the client.
<system.web>
<customErrors defaultRedirect="404.html" mode="RemoteOnly">
<error statusCode="404" redirect="/app" />
<error statusCode="500" redirect="/app" />
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" defaultResponseMode="File">
<clear />
<error statusCode="404" path="/app" responseMode="File" />
</httpErrors>
You must be logged in to post a comment.