React Router – Handling Page Refresh on the Server

Photo by visuals on Unsplash


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.


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 ^(.*)$$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" />

The section would fall in between the <system.web> tag.

    <customErrors mode="On">
      <error statusCode="404" redirect="/app" />

    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />



Or use the <rewrite> <rules> tags to handle page reloads.

<?xml version="1.0" encoding="UTF-8"?>
        <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 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" />
          <action type="Rewrite" url="/index.html" />

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.


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.

    <customErrors defaultRedirect="404.html" mode="RemoteOnly">
      <error statusCode="404" redirect="/app" />
      <error statusCode="500" redirect="/app" />
    <httpErrors errorMode="Custom" defaultResponseMode="File">
      <clear />
      <error statusCode="404" path="/app" responseMode="File" />