如何在 CentOS 7 上配置 Nginx 以使用自定义错误页面

介绍

Nginx 是一个高性能的 Web 服务器,能够提供灵活和强大的内容。在设计您的 Web 页面时,通常有助于自定义您的用户将看到的每个内容。这包括当他们请求内容时的错误页面。

前提条件

要开始使用本指南,您将需要具有)来设置此类用户。 您还需要在您的系统上安装 Nginx。 通过遵循 [此指南]来学习如何设置此功能(https://andsky.com/tech/tutorials/how-to-install-nginx-on-centos-7)。

创建你的自定义错误页面

我们将为示范目的创建一些自定义错误页面,但您的自定义页面显然会有所不同。

我们将我们的自定义错误页面放入/usr/share/nginx/html目录中,在那里 CentOS 的 Nginx 设置了其默认文件根。我们将为 404 错误创建一个页面,名为custom_404.html,并为一般 500 级错误创建一个页面,名为custom_50x.html

1echo "<h1 style='color:red'>Error 404: Not found :-(</h1>" | sudo tee /usr/share/nginx/html/custom_404.html
2echo "<p>I have no idea where that file is, sorry. Are you sure you typed in the correct URL?</p>" | sudo tee -a /usr/share/nginx/html/custom_404.html
3echo "<h1>Oops! Something went wrong...</h1>" | sudo tee /usr/share/nginx/html/custom_50x.html
4echo "<p>We seem to be having some technical difficulties. Hang tight.</p>" | sudo tee -a /usr/share/nginx/html/custom_50x.html

我们现在有两个自定义错误页面,我们可以服务客户端请求导致不同的错误。

配置 Nginx 以使用您的错误页面

现在,我们只需要告诉 Nginx 每当出现正确的错误条件时,它应该使用这些页面。我们需要调整我们的服务器块。在 CentOS 7,主服务器块位于 `/etc/nginx/nginx.conf 文件中。

1sudo nano /etc/nginx/nginx.conf

在文件内部,找到定义服务器背景的块,我们现在可以将 Nginx 指向我们的自定义错误页面。

将 404 错误导向自定义 404 页面

CentOS Nginx 配置文件已经使用),您创建的自定义页面得到服务。

 1[label /etc/nginx/nginx.conf]
 2http {
 3
 4    . . .
 5
 6    server {
 7
 8        . . .
 9
10        error_page 404 /custom_404.html;
11        location = /custom_404.html {
12            root /usr/share/nginx/html;
13            internal;
14        }
15
16        . . .
17    }
18}

通常情况下,我们不必在新位置块中设置,因为它与服务器块中的根相匹配,但是,我们在这里是明确的,所以即使我们将我们的常规网页内容和相关文档根移动到不同的位置,我们的错误页面也会被服务。

将 500 级错误直接发送到自定义 50x 页面

接下来,我们可以添加指南,以确保当 Nginx 遇到 500 级错误(服务器相关问题)时,它将服务于我们创建的其他自定义页面。

 1[label /etc/nginx/nginx.conf]
 2http {
 3
 4    . . .
 5
 6    server {
 7
 8        . . .
 9
10        error_page 404 /custom_404.html;
11        location = /custom_404.html {
12            root /usr/share/nginx/html;
13            internal;
14        }
15
16        error_page 500 502 503 504 /custom_50x.html;
17        location = /custom_50x.html {
18            root /usr/share/nginx/html;
19            internal;
20        }
21
22        location /testing {
23            fastcgi_pass unix:/does/not/exist;
24        }
25    }
26}

在底部,我们还添加了一个愚蠢的FastCGI通道,以便我们可以测试我们的500级错误页面。这不会正常工作,因为后端不存在。

保存并关闭文件,当你完成。

重新启动 Nginx 并测试您的页面

通过键入测试您的配置文件的语法:

1sudo nginx -t

如果报告了任何错误,请在继续之前修复它们。当没有返回语法错误时,请通过键入重新启动 Nginx:

1sudo systemctl restart nginx

现在,当您访问服务器的域或IP地址并要求一个不存在的文件时,您应该看到我们设置的404页面:

1http://server_domain_or_IP/thiswillerror

nginx custom 404

当您访问我们为 FastCGI 通道设置的位置时,我们将收到 502 Bad Gateway 错误,并在我们的自定义 500 级页面中显示:

1http://server_domain_or_IP/testing

nginx custom 50x

您现在可以回去并从您的 Nginx 配置中删除假的 FastCGI 通道位置。

结论

您现在应该为您的网站提供自定义错误页面,这是一个简单的方式来个性化用户的体验,即使他们遇到问题。 这些页面的一个建议是包括链接到他们可以寻求帮助或更多信息的地方。

Published At
Categories with 技术
Tagged with
comments powered by Disqus