記錄一次Nginx關於404頁面重定向的解決方案


前情提要

本地環境配置:

環境 版本號
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塊開啟,也可以在serverlocation塊開啟。為了便於區分,筆者將其開啟在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定義。類似的還可以添加狀態碼為500502503504時重定向的頁面,完整的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界面


大功告成!但一個好看的站點404頁面也一定是好看的,可以在網上尋找相關的資源,以后有空補鏈接。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM