2013-03-12 70 views
1

我有一個網站使用靜態html;沒有任何PHP或CGI服務可用。我想在javascript中構建一個有點智能的404錯誤頁面。從JavaScript: 404 page, how to get the requested url?我知道document.referer不可用於接收404頁面,但其中一個答案表明可能通過htaccess傳遞請求url。我該怎麼做?以下不工作:使用.htaccess和javascript處理404?

.htaccess

RewriteEngine on 
ErrorDocument 404 /err404.html?url=%{HTTP_REFERER} 

err404.html

<html><body> 
<script type="text/javascript"> 
    var file; 
    file = window.location.pathname; 
    document.write('sorry, ' + file + ' not found'); 
</script> 
<body></html> 

所顯示的網址仍然是進入相同,http://www.example.com/something-not-here

+0

它適用於我,即使沒有'?url =%{HTTP_REFERER}'(因爲我沒有重定向; url保持不變,但404文檔被加載)。 '/ err404.html'與你的根目錄相關,而不是'.htaccess'文件! – Christopher 2013-03-12 14:58:52

回答

1

啓用mod_rewrite的,並通過httpd.conf的.htaccess,然後把這個代碼在你.htaccessDOCUMENT_ROOT目錄:

Options +FollowSymLinks -MultiViews 
# Turn mod_rewrite on 
RewriteEngine On 
RewriteBase/

RewriteCond %{REQUEST_FILENAME} !-d # `!-d` means if directory doesn't exist 
RewriteCond %{REQUEST_FILENAME} !-f # if file doesn't ... 
RewriteCond %{REQUEST_FILENAME} !-l # if link doesn't 

# L = last rule, stop processing 
# QSA = Query String Append 
# R = Redirect (default is 302, temporary) 
RewriteRule^/err404.html?url=%{REQUEST_URI}&refr=%{HTTP_REFERER} [L,QSA,R] 

然後改變你的err404.html這樣的:

<html><body> 
<script type="text/javascript"> 
    function getQueryVariable(variable) { 
     var query = window.location.search.substring(1); 
     var vars = query.split('&'); 
     for (var i = 0; i < vars.length; i++) { 
      var pair = vars[i].split('='); 
      if (decodeURIComponent(pair[0]) == variable) { 
       return decodeURIComponent(pair[1]); 
      } 
     } 
     console.log('Query variable %s not found', variable); 
    } 
    document.write('sorry! ' + getQueryVariable('url') + 
        ' not found, requesting URL: ' + getQueryVariable('refr')); 
</script> 
<body></html> 

這將導致下面的文字顯示爲不存在的URIhttp://domain.com/not-here在頁面上http://domain.com/sample.html

sorry! /not-here not found, requesting URL: http://domain.com/sample.html 
+0

謝謝!這就給了我我正在尋找的東西 - 只是現在我擁有了它,我意識到它可能不是我應該做的!將斷開的鏈接保留爲斷開的鏈接(404而不是302)可能會更好。 @克里斯托弗的評論可能更接近核心。 – 2013-03-13 05:01:49

0

如果我理解正確的問題,這是因爲window.location將始終提供瀏覽器顯示的URL。重寫的URL僅在服務器端可用,因此您需要使用服務器端語言來完成此操作。