Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

IIS 自訂 404 錯誤頁面「URL 地址無效」解決:必須使用相對路徑

編輯:關於伺服器

問題現象

IIS 管理員 → 網站屬性 → **自訂錯誤** → 選 `404` → **編輯屬性** → 選 **URL** → 輸入 `https://www.example.com/404.html` → 提示:「錯誤的 URL 地址,請輸入一個站點的絕對 URL 地址」**。

根因

IIS 此處所謂的「絕對 URL」實為 **站點相對路徑 (Root-Relative Path)**,格式為 **`/404.html`** (以斜線開頭),**非完整網址 (https://...)**。

正確設定步驟

  1. 準備 `404.html` (或 `.asp`/`.aspx`/`.php`) 放入 **網站實體根目錄** (如 `C:\Inetpub\wwwroot\404.html`)。
  2. IIS 管理員 → 選中網站 → 右鍵 **內容** → **自訂錯誤** 索引標籤。
  3. 選中 `404` → 點擊 **編輯屬性...** (或雙擊)。
  4. 選擇 **URL** (非「檔案」或「預設」)。
  5. URL 欄位輸入: `/404.html` (前面必須有 `/`,不含域名、不含 `https://`)。
  6. 確定 → 確定 → 執行 `iisreset` (通常即時生效)。

進階:動態 404 頁面傳遞原始請求網址

若 404 頁面為動態腳本 (`.asp`/`.aspx`/`.php`),可接收 `QUERY_STRING` 參數 `404;https://example.com/bad-url`:

<!-- 404.asp 範例 --%>
<%
    Dim originalUrl
    originalUrl = Request.QueryString
    If InStr(originalUrl, "404;") = 1 Then
        originalUrl = Mid(originalUrl, 5)
    End If
%>
<html><body>
    <h1>404 - 頁面不存在</h1>
    <p>您請求的網址:<code><%=Server.HTMLEncode(originalUrl)%></code> 不存在。</p>
    <a href="/">返回首頁</a>
</body></html>

IIS 設定 URL 為 `/404.asp` 即可自動帶入參數。

ASP.NET (web.config) 統一錯誤處理 (更推薦)

<configuration>
  <system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="404" />
      <error statusCode="404" path="/404.aspx" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
  <system.web>
    <customErrors mode="On" defaultRedirect="/error.aspx">
      <error statusCode="404" redirect="/404.aspx" />
    </customErrors>
  </system.web>
</configuration>
  • `responseMode="ExecuteURL"`:伺服器端內部轉交,保持 404 狀態碼、網址不變。
  • `responseMode="Redirect"`:302 重導向,網址變為 `/404.aspx`,SEO 較差。

驗證測試

  1. 瀏覽 `https://your-site.com/不存在的頁面`。
  2. 檢查回應狀態碼:**必須為 404** (非 200、非 302)。
  3. 內容顯示自訂 404 頁面。
  4. 線上工具:站長工具 HTTP 狀態碼查詢。

常見誤區對照

輸入內容結果正確性
`https://www.site.com/404.html`提示「錯誤的 URL 地址」❌ 錯誤
`/404.html`正確導向站點根目錄下 404.html✅ 正確
`404.html` (無前導斜線)可能相對當前目錄,導致子目錄 404 失效⚠️ 不穩定
`\404.html` (反斜線)無效❌ 錯誤

總結

IIS 自訂錯誤頁面 URL 欄位**只接受站點根相對路徑 (以 `/` 開頭)**。輸入 `/404.html` 並確實將檔案放在網站實體根目錄,即可完美解決。現代 ASP.NET 應優先使用 `web.config ` 配置,功能更強、部署更簡單。

Copyright © Windows教程網 All Rights Reserved