0

如何强制Apache返回一个HTTP 410-状态码

Posted by 撒得一地 on 2015年12月24日 in Apache

我在我的站点删除了www.example.com/foo/file.html这个页面资源。但是,它仍然是被谷歌(Google)、雅虎(Yahoo)和许多其他机器人抓取。在CentOS / RHEL Fedora / Ubuntu / Debian和类unix操作系统上使用Apache Httpd服务器的站点,怎么返回一个http 410错误提示码,即告诉了这些机器人,你视图抓取的资源永久不存在了。

http 410错误状态码表明资源(图片、css、js和所有其他文件)永久失效。在使用的一个资源被故意删除或使用某种令牌,对于给定会话(例如缓存的pdf文件)生成特殊url,都有可能使用到410状态码。当接收到一个410状态码,客户端或机器人在未来不应该再请求该项资源。机器人等搜索引擎应该把资源从他们的索引中删除。

在下面的介绍中,你将学习Apache服务器如何快速返回HTTP状态码410,而不是404或403错误代码。

配置
最简单的配置方法,是使用使用mod_alias定向指令,在.htaccess文件中添加如下内容。切换 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*\.gif$"

# One more example. We now have resposive site so remove all old mobile friendly html pages
RedirectMatch gone "/mobilesite/*.html$"

添加友好消息页面

虽然Apache服务器对于访问错误或者不存在的资源返回4xx或者5xx HTTP状态代码,但是这些错误提示非常冷漠不友好,这些状态码传递的信息非常僵硬费解,甚至可能让网站的用户望而却步。你可以提供自定义错误提示,使用户体验更加友好。比如返回一些非英语的提示内容,或者是在返回内容中附加你网站特殊布局内容。所以你可以添加下面的代码:

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

在你的站点目录创建相应文件,在文件中编辑你要返回的内容:

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

在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 webmaster@example.com</small>
</blockquote>
</body>
</html>

上面内容保存后,当你的网站访问者,访问到一些永久删除的资源时,会看到这样页面提示:
HTTP/1.1 410 gone HTML page sample

验证错误状态码
用下面的命令可以验证错误状态码是否生效:

$ 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"状态码,那么在一个完整域名如何产生http-410错误码?

把以下内容添加到你的虚拟主机或.htaccess文件。这是通过使用mod_rewrite实现的:

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

最后保存文件。

英文地址:http://www.cyberciti.biz/faq/apache-return-a-http-410-error-resource-permanently-does-not-exist-configuration/

本文地址:http://coderschool.cn/1377.html

转载请注明本文地址和英文原文地址

标签:

上一篇:

下一篇:已是最新文章

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

8 + 3 = ?

网站地图|XML地图

Copyright © 2015-2024 技术拉近你我! All rights reserved.
闽ICP备15015576号-1 版权所有©psz.