DEV Community

Cover image for Configure nginx for Gatsby 404 error page
Bartosz Gordon
Bartosz Gordon

Posted on • Originally published at bartoszgordon.com

2 2

Configure nginx for Gatsby 404 error page

During Gatsby page development, when you hit a page that doesn't exist, you encounter a screen similar to the one below.

If you created a custom 404 page, for example in src/pages/404.js, you can click the Preview custom 404 page to display it. Entering the /404 route will do the job as well.


In production, however, the 404 page doesn't get handled by itself unless you use a dedicated hosting service for Gatsby pages. That's because Gatsby's development server is no longer present. The production bundle is just a bunch of static files. Making use of a web server (like nginx) to serve the production page forces you to configure the error pages yourself.

Disclaimer: the following nginx configuration is pretty basic, don't use it in production.

Let's assume your blog is hosted on the personalblog.com domain and is served from the /var/www/blog directory on port 80.

server {
        listen 80;
        root /var/www/blog;
        server_name personalblog.com www.personalblog.com;
        location / {
                try_files $uri $uri/ =404;
        }
}
Enter fullscreen mode Exit fullscreen mode

After entering a route that doesn't exist in your production Gatsby site, nginx displays its default 404 error page.

Adding the error_page 404 /404; line makes nginx redirect to the /404 route in case of a 404 error. Your custom Gatsby 404 page will be displayed.

server {
        listen 80;
        root /var/www/blog;
        server_name personalblog.com www.personalblog.com;
        error_page 404 /404;
        location / {
                try_files $uri $uri/ =404;
        }
}
Enter fullscreen mode Exit fullscreen mode

Visit the error_page docs section to explore the rest of the configuration options.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more