React/Angular Application showing 404 error on refresh

On Apache server, React Application works fine, but if you refresh a page, it shows 404 error. This is because the application use BrowserRouter. To fix the error, create a .htaccess file with following content

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [L]
ErrorDocument 404 /404.html

or following code, this results in http 200 for non-existant pages.

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

Put this on the folder where your application index.html is or in Apache Virtual Host entry.

In case of nginx, use

server {
    listen 80;
    server_name serverok.in;
    root /var/www/serverok.in;
    location / {
        try_files $uri $uri.html $uri/ =404;
    }
    error_page 404 /404.html;
    location = /404.html {
        internal;
    }
}

See htaccess

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *