WordPress 生成站点地图sitemap.xml+robots.txt配置+nginx伪静态
如果你有一点编程基础,可以用代码来生成站点地图, 如果没编程基础或倾向于使用插件来完成,这里推荐:https://cn.wordpress.org/plugins/www-xml-sitemap-generator-org/
一、在WordPress的根目录,创建sitemap.php 代码如下:
<?php
require('./wp-blog-header.php');
header("Content-type: text/xml");
header('HTTP/1.1 200 OK');
$posts_to_show = 1000;
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">'
?>
<url>
<loc><?php echo get_home_url(); ?></loc>
<lastmod>
<?php $ltime = get_lastpostmodified('gmt');$ltime = gmdate('Y-m-d\TH:i:s+00:00', strtotime($ltime)); echo $ltime; ?>
</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<?php
/* 文章页面 */
$myposts = get_posts( "numberposts=" . $posts_to_show );
foreach( $myposts as $post ) { ?>
<url>
<loc><?php the_permalink(); ?></loc>
<lastmod><?php the_time('c') ?></lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<?php } /* 文章循环结束 */ ?>
<?php
/* 单页面 */
$mypages = get_pages();
if(count($mypages) > 0) {
foreach($mypages as $page) { ?>
<url>
<loc><?php echo get_page_link($page->ID); ?></loc>
<lastmod><?php echo str_replace(" ","T",get_page($page->ID)->post_modified); ?>+00:00</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<?php }} /* 单页面循环结束 */ ?>
<?php
/* 博客分类 */
$terms = get_terms('category', 'orderby=name&hide_empty=0' );
$count = count($terms);
if($count > 0){
foreach ($terms as $term) { ?>
<url>
<loc><?php echo get_term_link($term, $term->slug); ?></loc>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<?php }} /* 分类循环结束 */?>
<?php
/* 标签(可选) */
$tags = get_terms("post_tag");
foreach ( $tags as $key => $tag ) {
$link = get_term_link( intval($tag->term_id), "post_tag" );
if ( is_wp_error( $link ) )
return false;
$tags[ $key ]->link = $link;
?>
<url>
<loc><?php echo $link ?></loc>
<changefreq>monthly</changefreq>
<priority>0.4</priority>
</url>
<?php } /* 标签循环结束 */ ?>
</urlset>
sitemap.php 创建完成,https://xxx.com/sitemap.php 查看,这个只是用来生成xml, 如果要想被搜索引擎使用,还需要在nginx里配置url重写转到sitemap.php,请参考下面nginx配置。
二、创建robots.txt, WordPress默认会在wp-includes/functions.php里的do_robots()方法生成robots.txt, 如果你有php编辑基础,可以在添加一些规则在里面,如果没有可以在WordPress根目创建robots.txt 内容如下:
User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
Sitemap: https://www.fujuhao.com/sitemap.xml
添加完后,我们就可以使用 https://xxx.com/robots.txt 查看。
三、搜索引擎访问的是sitemap.xml也就是我们在步骤二里配置的Sitemap:https://xxx.com/sitemap.xml,然后配置nginx url重写让搜索引擎找到我们的sitemap.php, sitemap.php生成xml数据返回,在nginx的配置文件里加入以下代码:
rewrite ^/sitemap.xml$ /sitemap.php last;
本站的 sitemap.xml https://fujuhao.com/sitemap.xml