PHP外链本地化及自动添加nofollow属性
做网站的都或多或少需要了解一点SEO的知识,在发文章的时候对于站外链接都想加上一个nofollow的属性,以防止本站的权重不流失,手动给每个链接增加nofollow有些费事,今天分享的PHP代码自动把非本站网址的链接加上nofollow属性。
首先添加下面代码到module.php
<?php function content_nofollow($log_content, $domain) { preg_match_all('/href="(.*?)" rel="external nofollow" /', $log_content, $matches); if ($matches) { foreach ($matches[1] as $val) { if (strpos($val, $domain) === false) { $log_content = str_replace('href="' . $val . '" rel="external nofollow" rel="external nofollow" ', 'href="' . $val . '" rel="external nofollow" rel="external nofollow" rel="external nofollow" ', $log_content); } } } preg_match_all('/src="(.*?)"/', $log_content, $matches); if ($matches) { foreach ($matches[1] as $val) { if (strpos($val, $domain) === false) { $log_content = str_replace('src="' . $val . '"', 'src="' . $val . '" rel="external nofollow"', $log_content); } } } return $log_content; }?>
然后到echo_log.php、page.php里替换<?php echo $log_content; ?>为下面代码
<?php echo content_nofollow($log_content,BLOG_URL);?>
另外一种方法是外链本地化
首先需要将下面的代码保留到redirect.php,并提交到网站根目录
<?php error_reporting(0); $url = $_GET['url']; header("Location:".$url); ?>
然后添加下面代码到module.php
<?php function content_nofollow($log_content, $domain){ preg_match_all('/href="(.*?)"/', $log_content, $matches); if ($matches) { foreach ($matches[1] as $val) { if (strpos($val, $domain) === false) { $log_content = str_replace('href="'.$val.'"', 'href="'.BLOG_URL.'redirect.php/?url='.$val.'"', $log_content); }}} preg_match_all('/src="(.*?)"/', $log_content, $matches); if ($matches) { foreach ($matches[1] as $val) { if (strpos($val, $domain) === false) { $log_content = str_replace('src="' . $val . '"', 'src="' . $val . '" rel="external nofollow"', $log_content); }}} return $log_content; }?>
最后到echo_log.php、page.php里替换<?php echo $log_content; ?>为下面代码
<?php echo content_nofollow($log_content,BLOG_URL);?>
完成后即可外链本地化了。
小指重新优化了外链本地化的方法,里面只有href才使用了外链本地化,src使用nofollow的方法,否则会出错哦!!!
小指亲测的啦^_^
点赞1
支持一下