解决使用 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/

EOF


荒原之梦网全部内容均为原创,提供了涵盖考研数学基础知识、考研数学真题、考研数学练习题和计算机科学等方面,大量精心研发的学习资源。

意见反馈 | 内容纠错 | 微信 | QQ | 公众号 | 知乎 | 微博 | 博客园 |CSDN | B 站 | 电子邮件
豫 ICP 备 17023611 号-1 | 公网安备 - 荒原之梦 豫公网安备 41142502000132 号 | SiteMap
Copyright © 2017-2024 ZhaoKaifeng.com 版权所有 All Rights Reserved.

Copyright © 2024   zhaokaifeng.com   All Rights Reserved.
豫ICP备17023611号-1
 豫公网安备41142502000132号

荒原之梦 自豪地采用WordPress