error_page 配置
大约 2 分钟
Error Page 配置
当访问资源不存在时,通常会返回 404 状态码来告诉访问者访问的资源不存在,但通常了为了使交互更友好,会选择直接返回一个页面来告知。
方法一: 配置全局的 404 页面
http {
#... ...
# 虚拟主机配置
server {
# 监听端口
listen 80;
# 服务主机名
server_name localhost;
# 本地文件目录
root /home/user/blog;
# 访问目录 http://localhost/
location / {
# 首页文件,访问 http://localhost/ 默认访问 index.html 文件
index index.html;
# 不匹配返回 404 状态码
try_files $uri $uri/ =404;
}
# 当出现404时,显示自定义404页面
error_page 404 /404.html;
# 定义404页面
location = /404.html {
# 页面是内部使用的,不能被外部直接访问,避免有人直接通过
internal;
}
}
#... ...
}
这种配置方式是通过状态码来寻找自定义的 404 页面,这个配置的好处在于它是全局通用,所有的 location 找不到资源时都是用的是这个 404 页面。
internal 指令
internal
指令的作用是声明该资源供 nginx 使用,外部不能直接通过地址访问。
方法二: 属于 location 的 404 页面
http {
#... ...
# 虚拟主机配置
server {
# 监听端口
listen 80;
# 服务主机名
server_name localhost;
# 本地文件目录
root /home/user/blog;
# 访问目录 http://localhost/blog/
location /blog/ {
# 首页文件,访问 http://localhost/blog/ 默认访问 index.html 文件
index index.html;
# 不匹配返回 404.html
try_files $uri $uri/ /404.html;
}
# 定义404页面
location = /404.html {
# 页面是内部使用的,不能被外部直接访问,避免有人直接通过
internal;
}
}
#... ...
}
在这个配置中,如果当前访问的资源不存在时,将会访问 /404.html
作为返回结果返回;但是,这个配置他仅限于访问 /blog/
这个 location 时资源找不到时才会返回,其它的 location 不会使用这个配置。