dd

在Nginx下设置正确的404自定义页面解决"软404"错误

十度 linux 2016年02月14日 收藏

换了VPS之后的某一天,在Google管理员工具控制台下看到了大量的"软404"错误,查找了一些资料之后发现是自己在Nginx下配置404页面的方法不对才导致了错误的产生,在此记录一下Nginx下正确的404页面配置方法。


404是一个相应代码,表示"页面无法找到"(Page Not Found),Google关于"软404"给出的说法是:

Instead of returning a 404 response code for a non-existent URL, websites that serve "soft 404s" return a 200 response code.


就是说对于那些不存在的URL,服务器并没有返回404(Page Not Found)代码,而是返回了200(OK)代码,而这是不正常的。


之后在其它的搜索结果里我又看到了这样一段话

Soft 404s can occur as a result of configuration errors when an Error Document 404 is specified as an absolute path rather than a relative path.

看完之后恍然大悟,因为我的404自定义页面是有图片和CSS的,而图片跟CSS都是以相对路径(eg. /xxx/xxx)写在页面里的,所以为了能让整站都能看到404页面里的图片,我就把404页面在Nginx里定义成了绝对路径(eg. //www.slyar.com/xxx/xxx),由于页面被当成了外部页面,所以会返回200代码,由此产生了"软404"错误。


知道了错误,那就好办了。将404页面的路径定义为相对路径,至于图片和CSS,只要在页面里使用绝对路径即可。

Nginx下正确的404页面定义方法:

1、VIM编辑Nginx配置文件,用了vhosts的就单独改,没用的直接改nginx.conf

vim  /usr/local/nginx/conf/nginx.conf
or
vim  /usr/local/nginx/conf/vhosts/slyar.com.nginx.conf

2、以相对路径指定404页面

server {
#error_page 404 //www.slyar.com/404.html
error_page  404 /404.html;
}

3、:wq保存退出,重新加载Nginx

/usr/local/nginx/sbin/nginx -s reload

4、重新检查一下不存在的页面,看是否返回404

curl -I //www.slyar.com/slyar
HTTP/1.1 404 Not Found
Server: nginx/1.0.15
Date: Mon, 27 Aug 2012 08:13:56 GMT
Content-Type: text/html
Content-Length: 2110
Connection: keep-alive


dd