WordPress 虚拟 robots.txt 文件

在 SEO 优化中 robots.txt 文件非常重要,当搜索引擎爬虫访问一个网站的时候,会先去查看这个文件,它可以告诉搜索引擎,那些页面不希望被搜索引擎索引,避免垃圾收录。

robots.txt 文件一般直接添加到网站的根目录即可(如https://pdbn.top/robots.txt)。而很多朋友会发现,根目录即使没有 robots.txt 文件,访问时也不是 404 找不到报错,而是出现了一些内容。

默认内容

User-agent: *
 Disallow: /wp-admin/
 Disallow: /wp-includes/

虚拟 robots.txt 文件

看到的默认内容,就是 WordPress 的虚拟 robots.txt 文件。利用 PHP 的伪静态机制,实现虚拟 robots.txt 文件,当根目录真有一个 robots.txt 文件时,虚拟的就会被 “覆盖” 掉。

如果你要给虚拟 robots.txt 文件添加内容的话,可以使用下边的代码,添加到主题的 functions.php 或者插件里即可。

/**
 *WordPress 虚拟 robots.txt 文件
 */
 function netnote_add_robots_txt( $output ){
 $output .= "Disallow: /wp-content/n";
 $output .= "Disallow: /index.phpn";
 $output .= "Disallow: /index.htmln";
 $output .= "Disallow: /cgi-bin/n";
 $output .= "Disallow: /*/feedn";
 return $output;
 }
 add_filter( 'robots_txt', 'netnote_add_robots_txt' );

使用虚拟 robots.txt 的好处

使用虚拟的 robots.txt 的好处就是在访问 robots.txt 的时候也会载入 WordPress 的代码,换句话说,任何插件和主题都可以对 robots.txt 进行修改,方便用户。

比如 Google XML Sitemaps 插件,可以利用虚拟 robots.txt 文件,自动帮你在 robots.txt 里引入网站地图,不用手动修改。

本站使用的就是虚拟的 robots.txt 文件,我觉得这种方式比较灵活。

来自https://www.endskin.com/invented-robots-txt/