修改 nginx.conf 添加 rewrite 规则,解决 WordPress Sitemap 插件生成的站点地图 404 问题

站点地图(sitemap)包含指向站内页面的链接,有助于搜索引擎索引网站,提高搜索展现量,从而提高点击量。站点地图对 SEO 的帮助很大,目前百度、谷歌、必应的站长平台都具有提交站点地图的功能。

WordPress 本身不包含生产站点地图的功能,所以我们需要采用第三方插件。好在这方面插件数量庞大,随手一搜都是广泛使用的插件:

wordpress sitemap插件

不过在使用插件的时候,我们很容易看到建议用户修改 Nginx 配置文件来解决 sitemap 文件无法加载的提醒。这对于一些新手站长来说有点困难,包括配置文件在哪里、代码添加到什么位置等等,都可能引起困扰。

本文以使用 OneinStack 脚本搭建的 LNMP 环境为例,主流 SEO 插件伪静态代码如下:

Yoast SEO

# Rewrites for Yoast SEO XML Sitemap
rewrite ^/sitemap_index.xml$ /index.php?sitemap=1 last;
rewrite ^/([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;

All In One SEO

# All In One SEO
rewrite ^/video-sitemap.xml$ /index.php?aiosp_video_sitemap_path=root last;
rewrite ^/video-sitemap.xml.gz$ /index.php?aiosp_video_sitemap_path=root last;
rewrite ^/(.+)-video-sitemap.xml$ /index.php?aiosp_video_sitemap_path=$1 last;
rewrite ^/(.+)-video-sitemap.xml.gz$ /index.php?aiosp_video_sitemap_path=$1 last;
rewrite ^/(.+)-video-sitemap(\d+).xml$ /index.php?aiosp_video_sitemap_path=$1&aiosp_sitemap_page=$2 last;
rewrite ^/(.+)-video-sitemap(\d+).xml.gz$ /index.php?aiosp_video_sitemap_path=$1&aiosp_sitemap_page=$2 last;

rewrite ^/sitemap.xml$ /index.php?aiosp_sitemap_path=root last;
rewrite ^/sitemap.xml.gz$ /index.php?aiosp_sitemap_path=root last;
rewrite ^/(.+)-sitemap.xml$ /index.php?aiosp_sitemap_path=$1 last;
rewrite ^/(.+)-sitemap.xml.gz$ /index.php?aiosp_sitemap_path=$1 last;
rewrite ^/(.+)-sitemap(\d+).xml$ /index.php?aiosp_sitemap_path=$1&aiosp_sitemap_page=$2 last;
rewrite ^/(.+)-sitemap(\d+).xml.gz$ /index.php?aiosp_sitemap_path=$1&aiosp_sitemap_page=$2 last;

rewrite ^/sitemap.rss$ /index.php?aiosp_sitemap_path=rss last;
rewrite ^/sitemap.latest.rss$ /index.php?aiosp_sitemap_path=rss_latest last;

Rank Math

# START Nginx Rewrites for Rank Math Sitemaps
rewrite ^/sitemap_index.xml$ /index.php?sitemap=1 last;
rewrite ^/([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;
# END Nginx Rewrites for Rank Math Sitemaps

网站的 nginx.conf 文件位置可能不同,OneinStack 环境下一般位于 /usr/local/nginx/conf/vhost 中。如果有多个站点,找到对应站点的 conf 文件进行编辑。以 idcbuy.conf 为例:

  1. 使用 vim 编辑配置文件
  2. 在最末尾的 } 前添加插件的 rewrite 代码
  3. 保存文件
  4. 使用 systemctl restart nginx 命令重启 Nginx

正常情况下,此时站点地图页面就已经可以正常访问了。

本文演示的是特定的插件和环境,如果使用的是其他工具,那么应该以实际为准(例如伪静态代码、nginx.conf 文件的位置),避免修改后出现问题。如果本文有不好理解的地方也可以在评论区回复,方便大家一起讨论和解决。

耕读君
耕读君

云时代的我们要学会“腾云驾雾”

文章: 185

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注