nginx Redirect 404 Errors to Homepage WordPress

There are quite a few WordPress plugins that help you manage your 404 errors to improve your SEO. 404 not found errors can arise from deleting old posts and not creating a redirect or from spambots. This guide shows you how to use nginx to redirect 404 errors to your WordPress homepage.

This guide requires nginx and root access so you can modify your nginx virtual hosts.

nginx Redirect 404 Errors to Homepage WordPress

Open your nginx virtual host

sudo nano /etc/nginx/sites-available/wp-bullet.com

Add this snippet in the server block

# define error page
error_page 404 = @notfound;

# error page location redirect 301
location @notfound {
    return 301 /;
}

If you do not want to do a 301 permanent redirect you can use a 302 temporary redirect instead

# define error page
error_page 404 = @notfound;

# error page location redirect 302
location @notfound {
    return 302 /;
}

In your php block put the fastcgi_intercept_errors set to on

Alternatively you can put it in nginx.conf in the http { block

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    # intercept errors for 404 redirect
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

For clarity, here is a sample nginx virutal host for WordPress with the additions above

server {
    listen 80;
    server_name wp-bullet.com;

    root /var/www/nginx/wp-bullet.com;
    index index.php index.html;

    access_log /var/log/nginx/wp-bullet.com.log;
    error_log /var/log/nginx/wp-bullet.com.error.log;

    location / {
        try_files $uri $uri/ /index.php?$args /;
    }

    # define error page
    error_page 404 = @notfound;

    # error page location redirect 301
    location @notfound {
        return 301 /;
    }

    location ~ \.php$ {
        include /etc/nginx/fastcgi_params;
        # intercept errors for 404 redirect
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~ /\.ht {
        deny all;
    }

    location = /nginx.conf {
        deny all;
    }
}

Verify your nginx virtual host syntax is valid

sudo nginx -t

If your syntax was OK then reload the nginx service

sudo service nginx reload

That should do it!

Sources

How do I Force Redirect All 404s to Homepage
nginx Return 301 Redirect on 404 Error
How to Configure 404s when Using LEMP and WordPress

2 thoughts on “nginx Redirect 404 Errors to Homepage WordPress”

  1. ( an addendum, this 301 redirect in the nginx block does not work on a specific theme, where could be the barrier? ) no 404.php de um theme, of a theme, I’m using this:

    It works fine, it redirects yes, but by this method(php!!), is it really doing with 301? to safely prevent 404 errors in google webmaster? It’s good SEO practice?

    Thanks

Comments are closed.