作为IT工程师,我将为您详细介绍如何配置和美化Nginx的错误页面,提升用户在遇到网站故障时的体验。
在Nginx配置文件中(通常在/etc/nginx/nginx.conf
或站点配置文件中)添加:
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
创建HTML文件(如/usr/share/nginx/html/404.html
):
<!DOCTYPE html>
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>404 Not Found</h1>
<p>The page you requested could not be found.</p>
</body>
</html>
创建CSS文件(如/usr/share/nginx/css/error.css
):
body {
font-family: 'Arial', sans-serif;
background-color: #f8f9fa;
color: #343a40;
line-height: 1.6;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
text-align: center;
}
.error-container {
max-width: 600px;
padding: 2rem;
background: white;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
h1 {
color: #dc3545;
font-size: 2.5rem;
margin-bottom: 1rem;
}
p {
font-size: 1.2rem;
margin-bottom: 2rem;
}
a {
color: #007bff;
text-decoration: none;
font-weight: bold;
}
a:hover {
text-decoration: underline;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 Not Found</title>
<link rel="stylesheet" href="/css/error.css">
<link rel="icon" href="/favicon.ico">
</head>
<body>
<div class="error-container">
<h1>404</h1>
<p>Oops! The page you're looking for doesn't exist.</p>
<p><a href="/">Return to Homepage</a></p>
</div>
</body>
</html>
error_page 404 /error.php?code=404;
error_page 500 /error.php?code=500;
然后创建error.php
:
<?php
$errorCode = $_GET['code'] ?? '404';
$messages = [
'400' => 'Bad Request',
'401' => 'Unauthorized',
'403' => 'Forbidden',
'404' => 'Not Found',
'500' => 'Internal Server Error',
'502' => 'Bad Gateway',
'503' => 'Service Unavailable',
'504' => 'Gateway Timeout'
];
$title = $errorCode . ' ' . ($messages[$errorCode] ?? 'Error');
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo htmlspecialchars($title); ?></title>
<link rel="stylesheet" href="/css/error.css">
</head>
<body>
<div class="error-container">
<h1><?php echo htmlspecialchars($errorCode); ?></h1>
<p><?php echo htmlspecialchars($messages[$errorCode] ?? 'An error occurred'); ?></p>
<p><a href="/">Return to Homepage</a></p>
</div>
</body>
</html>
server {
error_page 404 /404.html;
location = /404.html {
internal;
if ($http_accept ~* "application/json") {
return 404 '{"error": "Not Found", "code": 404}';
}
if ($http_accept ~* "application/xml") {
return 404 '<?xml version="1.0"?><error><code>404</code><message>Not Found</message></error>';
}
}
}
map $http_accept_language $lang {
default en;
~*^zh zh;
~*^fr fr;
}
server {
error_page 404 /error/$lang/404.html;
}
error_page 404 = @error_404;
location @error_404 {
proxy_pass http://error_service;
internal;
}
配置完成后,使用以下命令测试并重载Nginx:
sudo nginx -t # 测试配置语法
sudo systemctl reload nginx # 重载配置
您可以通过访问不存在的URL来测试404页面,或使用工具如curl测试不同错误代码:
curl -I http://yoursite.com/nonexistent-page
通过以上配置和美化,您的网站在遇到故障时将提供更专业、友好的用户体验。