如何强制Apache显示HTTP-410消失状态代码

时间:2020-01-09 10:37:10  来源:igfitidea点击:

我从网域中删除了www.example.com/foo/file.html。
但是,它仍然被Google /雅虎和许多其他机器人抓取。
如何返回HTTP-410消失的错误,即告诉这些漫游器在CentOS/RHEL/Fedora/Ubuntu/Debian和类似Unix的操作系统上使用Apache HTTPD服务器永久不存在资源?

http错误状态代码410指示请求的资源(图像,css,js和所有其他文件)不再可用,并且将永远不再可用。
当有意删除资源或使用给定会话的某种令牌生成的唯一URL的一部分(例如,缓存的pdf文件)时,可以使用此410状态代码。
收到410状态代码后,客户端或漫游器以后就不应再请求资源。
诸如搜索引擎之类的机器人应从其索引中删除资源。
在本快速教程中,您将学习如何从Apache提供HTTP状态代码410,而不是404或403错误代码。

组态

最简单的配置是使用mod_alias Redirect指令在.htaccess文件中添加以下行。

CD到您的DocumentRoot,例如/var/www/html /:

$ cd /var/www/html/
$ vi .htaccess

追加以下行:

Redirect gone /foo/file.html

要么

Redirect 410 /foo/bar/demo.php

您还可以使用RedirectMatch指令使用正则表达式,如下所示:

# Syntax 
RedirectMatch gone regex-here
 
# Match all .png files in /foo/
RedirectMatch gone "/foo/\.png$"
 
# Another example for gif files starting with bar name
RedirectMatch gone "/foo/bar*\.png$"
 
# One more example. We now have resposive site so remove all old mobile friendly html pages
RedirectMatch gone "/mobilesite/*.html$"

添加友好的消息页面

尽管在出现4xx或5xx HTTP状态代码的情况下,Apache Server会鄙视一般的错误响应,但是这些响应相当明显,毫无意义,并且可能使站点用户感到恐惧。
您可能希望提供更友好的自定义错误响应,或者以英语以外的其他语言提供自定义错误响应,或者提供的样式可能更符合您的网站布局。
因此,添加以下代码:

ErrorDocument 410 /errorpages/410-mobile.gone.html

保存并关闭文件。
接下来在DocumentRoot目录中创建410-mobile.gone.html(例如,/var/www/html/errorpage /)

$ mkdir /var/www/html/errorpage/ && cd $_
$ vi 410-mobile.gone.html

根据您的需要追加错误消息:

<html>
<head>
   <title>Page Gone - 410 Error</title>
</head>
<body>
<blockquote>
<h1>Error 410 - Page deleted or gone</h1>
This might be because:
<ul>
  <li>You have typed the web address incorrectly, or the page you were looking for may have deleted.</li>
</ul>
Please try the following options instead:
<ul>
  <li>Use <a href="/search.html">search option</a> to see if it's available elsewhere. Or visit our home page for the latest info.</li>
</ul>
<hr>
<small>If you feel like it, mail the url, and where you came from to [email protected]</small>
</blockquote>
</body>
</html>

您的访客将看到以下页面以及HTTP/1.1 410消失状态代码:HTTP/1.1 410消失HTML页面示例

验证错误代码

只需键入以下curl命令:

$ curl -I www.example.com/foo/page.html
$ curl -I www.example.com/mobilesite/4242.html

输出示例:

HTTP/1.1 410 Gone
Server: Apache
Date: Mon, 14 Dec 2015 14:52:28 GMT
Content-Type: text/html
Content-Length: 335
Connection: keep-alive

请注意,您必须获得HTTP/1.1 410 Gone作为状态代码。

如何为完整域生成HTTP-410错误?

将以下内容添加到您的VirtualHost或.htaccess中。
这是使用mod_rewrite完成的:

RewriteEngine On
   RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC]
   RewriteRule ^(.*)$ - [L,G]

保存并关闭文件。