繁体   English   中英

如何使用 .htaccess 重定向页面但也将其用作 W3 包括

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM