解决使用 YoastSEO 生成的 XML 站点地图报 404 Not Found 的问题

解决使用 YoastSEO 生成的 XML 站点地图报 404 Not Found 的问题

操作环境

服务器操作系统:Ubuntu Linux

Web 服务器:Nginx 或 Apache

Web 应用:WordPress

我使用的固定链接形态为“朴素”型,如下:

https://zhaokaifeng.com/?p=3095

问题描述

我在我的个人网站上安装了 YoastSEO, 但是开启其 XML Sitemap 功能后,访问:https://zhaokaifeng.com/sitemap_index.xml
却出现了 “404 Not Found” 的提示。

问题分析

YoastSEO 生成的 XML Sitemap 地址一般是这样的:

https://zhaokaifeng.com/sitemap_index.xml

但其实,在上面这个地址的背后,YoastSEO 生成的 XML Sitemap 的真实地址是这样的:

https://zhaokaifeng.com/?sitemap=1

因此,如果你能通过 example.com/?sitemap=1 正常打开 XML Sitemap, 那就说明你的 XML Sitemap 已经生成了,但是服务器的重写没有生效。这种情况下,我们可以使用下面的方法在 Nginx 或者 Apache 上解决该问题。

Nginx 服务器解决方案

登录服务器,进入 /etc/nginx/sites-available 目录,编辑 default 文件 (重要提示:编辑前请做好备份,以便需要时回滚数据!!!),将如下代码写入当前站点正在使用的 Server{} 块中:

#Yoast SEO Sitemaps

location ~ ([^/]*)sitemap(.*).x(m|s)l$ {

## this rewrites sitemap.xml to /sitemap_index.xml

rewrite ^/sitemap.xml$ /sitemap_index.xml permanent;

## this makes the XML sitemaps work

rewrite ^/([a-z]+)?-?sitemap.xsl$ /index.php?yoast-sitemap-xsl=$1 last;

rewrite ^/sitemap_index.xml$ /index.php?sitemap=1 last;

rewrite ^/([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;

}

之后重启 Nginx 服务器:

service nginx restart

此时再访问 https://zhaokaifeng.com/sitemap_index.xml 就可以看到 XML 站点地图已经能够正常显示,如图 1:

图 1. 荒原之梦的站点地图首页

Apache 服务器解决方案

如果你使用的 Web 服务器是 Apache, 则可以在 .htaccess 文件中 WordPress 重写规则的下面添加如下重写规则:

# Yoast SEO - XML Sitemap Rewrite Fix

RewriteEngine On

RewriteBase /

RewriteRule ^sitemap_index.xml$ /index.php?sitemap=1 [L]

RewriteRule ^locations.kml$ /index.php?sitemap=wpseo_local_kml [L]

RewriteRule ^geo_sitemap.xml$ /index.php?sitemap=geo [L]

RewriteRule ^([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 [L]

RewriteRule ^([a-z]+)?-?sitemap.xsl$ /index.php?yoast-sitemap-xsl=$1 [L]

# END Yoast SEO - XML Sitemap Rewrite Fix

References:
[1]. My sitemap is giving a 404 error, what should I do? • Yoast
https://yoast.com/help/my-sitemap-is-giving-a-404-error-what-should-i-do/
[2]. Yoast XML Sitemaps on NGINX servers • Yoast
https://yoast.com/help/xml-sitemaps-nginx/
[3]. Yoast XML Sitemaps on Apache servers • Yoast
https://yoast.com/help/xml-sitemaps-apache/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值