Nginx allows you to set up custom error pages for different HTTP status codes. Custom error pages can help improve the user experience by providing more informative and user-friendly error messages. Here's how you can configure custom error pages in Nginx:
Basic custom error pages:
Set up custom error pages for specific HTTP status codes.
server {
listen 80;
server_name yourdomain.com;
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location / {
# Your main configurations...
}
location = /404.html {
root /path/to/your/error/pages;
internal;
}
location = /50x.html {
root /path/to/your/error/pages;
internal;
}
}
In this example, requests returning a 404 status code will be redirected to /404.html, and requests returning a 500, 502, 503, or 504 status code will be redirected to /50x.html. The error_page directive specifies the error code and the corresponding URL.
Global custom error pages:
Set up global custom error pages for all server blocks.
http {
# ... Other configurations ...
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /404.html {
root /path/to/your/error/pages;
internal;
}
location = /50x.html {
root /path/to/your/error/pages;
internal;
}
# ... Server blocks and other configurations ...
}
This configuration sets up global custom error pages that will be used across all server blocks in your Nginx configuration.
Dynamic error pages with FastCGI:
Use a dynamic error page generated by a FastCGI script.
server {
listen 80;
server_name yourdomain.com;
error_page 404 /error.php;
location / {
# Your main configurations...
}
location = /error.php {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
internal;
}
}
In this example, requests returning a 404 status code will be redirected to a dynamic error page generated by a PHP script (error.php).
Redirect to a different domain:
Redirect users to a different domain for certain error pages.
server {
listen 80;
server_name yourdomain.com;
error_page 404 =301 http://newdomain.com/404.html;
location / {
# Your main configurations...
}
}
This example redirects users to http://newdomain.com/404.html if they encounter a 404 error.
Conclusion
Custom error pages can be HTML files, static files, or dynamic pages generated by scripts. Ensure that the paths specified in the error_page directive are correct and accessible. Test your configurations to ensure that the custom error pages are displayed as expected.