BLOG

Fix React Router 404 Errors on Hostinger

React Router app works until someone refreshes or follows a direct link, then 404. The .htaccess fix for Hostinger and other Apache hosts.

I deployed my portfolio and found that typing /blog straight into the address bar gave me a 404. Clicking around inside the app was fine. Refreshing, or arriving from a direct link, broke it completely.

Two routers, one of them blind

When someone types yourdomain.com/blog into their browser, the request hits your server first. The server looks for a file or directory called "blog", and there isn't one. Your routes live in React Router, not on disk. 404.

Clicking links inside the app works because React Router intercepts them and handles them in the browser, so the server never hears about it. A direct URL or a refresh goes to the server first, and the server has never heard of React Router.

The fix: .htaccess

After trying a few things I settled on an .htaccess file. It works on Hostinger, where this site lives, and on most other Apache hosts.

# Enable rewriting
RewriteEngine On

# If the request is not for a real file or directory
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all requests to the root index.html
RewriteRule ^ index.html [QSA,L]

Put this in your public directory before deploying.

What it does

The server now serves index.html for any URL that isn't a real file or folder. User visits yourdomain.com/blog, server returns index.html, React loads, React Router reads the URL and renders the blog page.

Other hosts

.htaccess covers most traditional hosts. Some platforms have their own mechanism: Netlify uses a _redirects file with /* /index.html 200, Vercel wants rewrites in vercel.json, and Firebase wants rewrites in firebase.json.

I'd still ship the .htaccess as a fallback. It costs nothing to have it sitting there.

With it in place, /blog loads from a refresh, a bookmark, or a link someone pasted somewhere, and crawlers that request the URL directly get a real page back instead of a 404.