前情提要
本地环境配置:
环境 | 版本号 |
---|---|
PHP | 7.3.6 |
Nginx | 1.17.0 |
闲来无事, 折腾了一下本地环境, 突然想到应该要搞一个 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;
- }
- }
重启 Nginx 服务器, 在浏览器的地址栏输入: 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 页面也一定是好看的, 可以在网上寻找相关的资源, 以后有空补链接.
来源: http://www.bubuko.com/infodetail-3204442.html