[英]How to use .htaccess to redirect a page but also use it as a W3 include
我正在使用 w3schools 此處顯示的包含方法構建 html 站點
https://www.w3schools.com/howto/howto_html_include.asp
該網站基本上如下所示
<div w3-include-html="navigation.html"></div>
<body>
</body>
<div w3-include-html="footer.html"></div>
當您在網站的正確頁面上時效果很好,但是如果我直接導航到 navigation.html,它會顯示一個看起來很糟糕且無用的頁面。
我嘗試使用類似以下內容的 .htaccess 文件重定向它,以便用戶可以優雅地登陸一個頁面,上面寫着對不起,這不存在,點擊這里等等等等。
重定向 /navigation.html /page-not-found.html
但是,這最終導致我所有真實頁面上的導航欄在 page-does-not-exist.html 頁面中顯示 html 頁面。
有沒有一種簡單的方法可以使用 .htaccess 將直接輸入www.example.com/navigation.html的用戶重定向到www.example.com/page-not-found.ZFC35FDC70D5FC69D269883A822C仍然允許其他頁面包含 A正常嗎?
感謝您提供的任何幫助。
This method uses JavaScript ( XMLHttpRequest
object, ie. "AJAX") to make an HTTP request for the document on the server. 通常,這與客戶端可能通過直接為文件鍵入 URL 發出的直接請求沒有什么不同(從服務器的角度來看)。
您需要使 JavaScript 請求不同。
You can add a custom HTTP request header (or override the User-Agent
string) to the JavaScript request and check for this header using mod_rewrite in .htaccess
on the server to send an alternative response if the file is requested directly, ie. 當 header 不存在或按預期設置時。
例如,根據 w3schools 的代碼,在創建XMLHttpRequest
object 之后添加第二行:
xhttp = new XMLHttpRequest();
xhttp.setRequestHeader('User-Agent','XMLHTTP');
這會將 JS 請求中的User-Agent
header 設置為XMLHTTP
。 然后,我們可以使用 mod_rewrite 進行檢查,如果未設置,則提供 404。
但是,您不應“重定向”到page-not-found.html
腳本。 將此設置為自定義 404 錯誤文檔,並允許 Apache 提供此服務。
例如:
ErrorDocument 404 /page-not-found.html
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} !=XMLHTTP
RewriteRule ^navigation\.html$ - [R=404]
User-Agent
字符串不是XMLHTTP
的/navigation.html
的任何請求都將提供自定義 404 錯誤文檔,即。 /page-not-found.html
。 因此,只允許來自您的腳本的請求。
注意:這不是一項安全功能,它只是防止隨便在瀏覽器中鍵入 URL 的人看到內容(包括搜索引擎)。
在旁邊:
<div w3-include-html="navigation.html"></div> <body> </body> <div w3-include-html="footer.html"></div>
由此看來,您在 HTML body
之外包含了 HTML 元素? 這不是有效的 HTML。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.