在 web.config 中設定 <customErrors> 導向自訂 404 頁面時,瀏覽器實際收到的 HTTP 狀態碼卻是 302 Found(重導向),而非預期的 404 Not Found。這對 SEO 極為不利:搜尋引擎會認為頁面仍存在,只是暫時重導向,導致錯誤頁面被索引、權重分散。
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
Response.StatusCode = 404;
Response.StatusDescription = "Not Found";
// 或一行寫法:Response.Status = "404 Not Found";
}
</script>
若專案未啟用 URL 重寫(偽靜態),此步驟通常已足夠。
啟用偽靜態(如 URL Rewrite、Wildcard Mapping)時,ASP.NET 管線會先重導向再執行 404.aspx,導致狀態碼被重置為 302。需在 Global.asax 中攔截 404 例外並使用 Server.Transfer 內部轉交,避免客戶端重導向。
protected void Application_Error(object sender, EventArgs e)
{
FileNotFound_Error();
}
private void FileNotFound_Error()
{
var httpEx = Server.GetLastError() as HttpException;
if (httpEx != null && httpEx.GetHttpCode() == 404)
{
Server.ClearError();
Server.Transfer("~/404.aspx"); // 內部轉交,URL 不變,狀態碼保持 404
}
}
Response.Redirect / customErrors redirect:發送 302 給瀏覽器,瀏覽器再請求新 URL → 狀態碼變 200。Server.Transfer:伺服器端內部轉交,瀏覽器 URL 不變,原始請求的狀態碼可由目標頁面(404.aspx)覆寫為 404。Server.ClearError():清除例外,避免觸發預設錯誤處理流程。/notexist.aspx)。httpstatus.io)檢測同一 URL,確保返回 404。<system.web>
<customErrors mode="On" defaultRedirect="~/Error.aspx">
<error statusCode="404" redirect="~/404.aspx" />
<error statusCode="500" redirect="~/Error.aspx" />
</customErrors>
</system.web>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" />
<error statusCode="404" path="/404.aspx" responseMode="ExecuteURL" />
</httpErrors>
</system.webServer>
system.webServer/httpErrors 針對 IIS 7+ 管線模式下的靜態檔案、PHP 等非 ASP.NET 請求也能生效。
結合 404.aspx 設定 Response.StatusCode = 404 與 Global.asax 使用 Server.Transfer,即可徹底解決 ASP.NET 404 頁面返回 302 的頑固問題,確保 SEO 友善與使用者體驗雙贏。