记录一次Nginx关于404页面重定向的解决方案
闲来无事,折腾了一下本地环境,突然想到应该要搞一个404页面让网站显得专业一点(看起来牛批一点),开始Google:Nginx该如何配置自己的404页面。好的,以下是试验过后的解决方案:
这里先贴一下nginx.conf
来避免以后遗忘:
worker_processes 4; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; sendfile on; keepalive_timeout 65; client_max_body_size 100m; gzip on; include vhost/*.conf; upstream fastcgi_proxy { server 127.0.0.1:9000; server 127.0.0.1:9001; } }
其中很重要的一句配置是include vhost/*.conf;
,它表示“nginx服务器将寻找vhost
目录下后缀为.conf
的文件并包含在nginx.conf
配置文件中”。通常用来配置虚拟服务,一个文件只包含一个server
块,以保持其独立性,也避免nginx.conf
配置文件过长以至于不清晰的问题。
现在开始配置404页面。先上一个普通虚拟站点的server
配置:
server { listen 80;# 监听端口:一般是80 server_name front;# 虚拟域名:配置后重启Nginx服务器,在浏览器输入 http://front 即可访问在 root 目录下的站点 root E:/rep/front;# 网站根目录 charset utf-8; location / { index index.html index.php; } # 开启PHP-CGI解析 location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
然后开始配置404页面:
开启Nginx的fastcgi_intercept_errors
错误自定义选项
这个配置可以在http
块开启,也可以在server
、location
块开启。为了便于区分,笔者将其开启在server
块,使每个服务器都有其独有的404页面。
在server
块中添加如下代码:
fastcgi_intercept_errors on;# 开启支持错误自定义
自定义404页面的位置
在网站根目录找个合适的位置存放404.html
文件,笔者这里是/page/404.html
。然后在server
块继续添加以下代码:
error_page 404 /page/404.html; location = /page/404.html { root E:/rep/front; }
不要忘记添加该位置页面的root
定义。类似的还可以添加状态码为500
、502
、503
和504
时重定向的页面,完整的server
块配置如下:
server { listen 80; server_name front; root E:/rep/front; charset utf-8; location / { index index.html index.php; } fastcgi_intercept_errors on;# 开启支持错误自定义 error_page 404 /page/404.html; location = /page/404.html { root E:/rep/front; } error_page 500 502 503 504 /page/50x.html; location = /page/500.html { root E:/rep/front; } # 开启PHP-CGI解析 location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
http://front/jdsahjadjsaldjadsa
(确保该域名已加入host
文件),可以看到你定义的404界面:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>404</title> </head> <body> <h1>404</h1> </body> </html>

大功告成!但一个好看的站点404页面也一定是好看的,可以在网上寻找相关的资源,以后有空补链接。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析