Solved NGINX Redirect 404 Errors to WordPress Homepage
I will be sharing with you step by step tutorial to work with nginx server to redirect 404 (not found) web page to WordPress homepage.
Before we begin, a user must have root access using SSH credentials. It allows user to update nginx virtual host.
NGINX Redirecting 404 Error to WordPress Homepage
Hit the below command to open nginx virtual host.
sudo nano /etc/nginx/sites-available/positronx.io
Include the given below code in the nginx server block file.
# added error page
error_page 404 = @notfound;
# 301 permanent redirection
location @notfound {
return 301 /;
}
We used 301 redirections in the above code example just like that we can also implement 302 temporary redirection using NGINX virtual server host.
# added error page
error_page 404 = @notfound;
# 301 temporary redirection
location @notfound {
return 302 /;
}
There are 2 ways through which you can set fastcgi_intercept_errors
to on state.
1 – You can go to php block and set fastcgi_intercept_errors to on like given below.
fastcgi_intercept_errors on;
2 – You can go to /etc/nginx/nginx.conf
file and include within the http { } code block.
# /etc/nginx/nginx.conf
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
# errors for 404 redirect
fastcgi_intercept_errors on;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
server {
listen 80;
server_name positronx.io www.positronx.io;
root /var/www/nginx/positronx.io;
index index.php index.html;
access_log /var/log/nginx/positronx.io.log;
error_log /var/log/nginx/positronx.io.error.log;
location / {
try_files $uri $uri/ /index.php?$args /;
}
# added error page
error_page 404 = @notfound;
# 301 permanent redirection
location @notfound {
return 301 /;
}
location ~ \.php$ {
include /etc/nginx/fastcgi_params;
# errors for 404 redirect
fastcgi_intercept_errors on;
fastcgi_pass unix:/run/php/php7.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
location = /nginx.conf {
deny all;
}
}
Use the below command to find out if your changes get some errors in nginx virtual host.
sudo nginx -t
If you get this message in your terminal this means you are ready to reload the nginx server.
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
Enter the below command to reload the nginx server
sudo service nginx reload