1. You have set the page (or the whole post type) to
noindex. 2. The page’s canonical URL is set to a different URL.
3. The page was redirected to another URL by Yoast SEO Premium.
4. If it’s the news sitemap, the page has not been published within the past 48 hours.
noindex, go to the Advanced tab in the Yoast SEO metabox or sidebar, and make sure you allow search engines to show the page in the search results. To check the settings for the whole content type/taxonomy, go to the Advanced settings in Yoast SEO and ensure you are not blocking search engines from accessing your content. 2. To check if the page’s canonical URL is set to a different URL, use the URL inspection tool and follow Google’s guidelines on consolidating duplicate URLs.
3. If you are using Yoast SEO premium, check if the page was redirected to another URL in Yoast’s redirect manager.
Viewing 15 replies — 1 through 15 (of 15 total)
Can you first confirm that the XML Sitemaps feature is enabled in the pugin In order to enable sitemaps in the Yoast SEO plugin, you would need to perform the following actions:
- In WordPress go to SEO>General>Features
Toggle the ‘XML Sitemaps’ option to ‘On’
Click ‘Save Changes’
If you have confirmed that sitemaps are enabled and you are still receiving a 404 error at sitemap_index.xml, the error can be caused by a number of issues, including the permalinks or rewrite rules. We would first recommend to try resetting the permalink structure in WordPress which can be done by performing the following steps:
- In WordPress, go to Settings>Permalinks
Clicking ‘Save Changes’ without making any modifications
We also have additional information regarding the sitemap files creating an error here: https://kb.yoast.com/kb/my-sitemap-index-is-giving-a-404-error-what-should-i-do/
If you continue to receive the error after resetting the permalinks, we would then also suggest adding a set of rewrite rules to your server and we have a guide on adding these for an Apache servers here: https://kb.yoast.com/kb/xml-sitemaps-apache/ and for Nginx servers here: https://kb.yoast.com/kb/xml-sitemaps-nginx/.
Thread Starter
Javier
(@vaporlibre)
I did all the steps, but the same thing still happens to me, It doesn’t give me a 404 error, it simply redirects me to my homepage, what can I do?
- This reply was modified 2 years, 10 months ago by
Javier.
Hi,
We can see that the redirect from the Yoast sitemaps https://vaporlibre.com/sitemap_index.xml to the homepage is coming from the server. We suggest contacting your host provider and verifying that the server is correctly configured and no rules exist which are resulting in that behavior.
Thread Starter
Javier
(@vaporlibre)
I checked the entire server, hired an informatic, I also talked to the administrators of the server and everything is correct, they say it is a plugin problem, reading in the forums I have seen that this happens to many people too.
Hi,
We are not sure why the Yoast sitemaps are failing to appear. But it now sounds like a plugin or theme conflict. Can you try and gather as much information for us as possible? Please perform the following:
1. Make sure you are using the most recent WordPress Core, v5.3.2. If you are not sure what version you have or how to update, your host provider can help. Also, be sure to update your Yoast to v13.2 and update your non-Yoast plugins.
2. Please Check for conflicts.
If there is a conflict with a plugin or a theme, you can create a new GitHub issue for our developers. Please report the issue to a third party developer as well.
If you didn’t find any conflicts or errors, we think the issue is specific to your site. We’d need to investigate further but are unable to do so on these forums. You can purchase Yoast SEO Premium and receive our Premium email support and we can help you further.
Thread Starter
Javier
(@vaporlibre)
I checked all that he told me, nothing works. Previously it worked correctly, it was in an update when it stopped working.
How do you want me to buy the premium version, if the free one doesn’t work?
Yoast SEO sitemaps can be loaded using two URLs, the pretty permalink one and a non-pretty permalink.
Pretty Permalink: https://www.example.com/sitemap_index.xml
Non-Pretty Permalink: https://www.example.com/?sitemap=1
The pretty permalink redirects to the homepage. Please check any redirect plugins you may have and remove redirects that are causing this redirect.
The non-pretty permalink returns an error XML declaration allowed only at the start of the document. Multiple blank line appear in the source code of the sitemap and is due to a conflict with something in your setup. Usually, there is an empty space or a blank line before or after the closing PHP opening or closing tag, which shouldn’t be there.
You can narrow down the exact source of conflict by performing a conflict check. Once you have identified whether your theme or a plugin causes the issue, please contact the developers of that theme or plugin for assistance in finding and removing the whitespace.
Test this on your development or staging site, if you have one. If not, we recommend using the Health Check & Troubleshooting plugin. This plugin allows you to run a conflict check without affecting normal visitors to your site.
As we can imagine that you’re unfamiliar with checking for conflicts, we’d like to point you to a step-by-step guide that will walk you through the process: How to check for plugin conflicts.
All URLs which end with ‘xml’ redirect to front page:
$ curl -i https://vaporlibre.com/sitemapblablablablaxml
HTTP/1.1 301 Moved Permanently
Server: nginx
...
X-Powered-By: PHP/7.3.15
X-Redirect-By: WordPress
...
If you can’t find PHP code or a plugin then you can try to use https://github.com/stracker-phil/wp-debug-redirect. It’ll show debug trace in HTTP headers.
Other issue is white-space:
$ curl -i https://vaporlibre.com/?sitemap=1
HTTP/1.1 200 OK
Server: nginx
Content-Type: text/xml; charset=UTF-8
...
X-Powered-By: PleskLin
<?xml version="1.0" ...
There are 4 empty lines before the content. You should find them into the code or plugins. I think that the theme isn’t source of the white-space.
Thread Starter
Javier
(@vaporlibre)
How can I remove those 4 blanks, I have reviewed all the plugins, and all the files in my root, but nothing.
The problem is that the document is not created on my server to modify it.
I still see redirects…
Yoast SEO generates sitemaps “on the fly” and there aren’t physical XML files. You can’t just open XML file and remove lines.
Empty lines in PHP files can be located anywhere (even on the end of files). Common places are wp-config.php and functions.php.
You should try https://yoast.com/help/how-to-check-for-plugin-conflicts/ You should open two tabs (admin dashboard and sitemap) in the browser. At second tab (sitemap) try to force refresh (ctrl-f5) at each activation/deactivation of plugin.
If you aren’t familiar with this process then you can see video – https://givewp.com/documentation/resources/troubleshoot-wordpress-websites-health-check/
Thread Starter
Javier
(@vaporlibre)
I managed to remove all the spaces, now the file is seen correctly.
But I have another problem, it tells me that the file has html tag.
And the url doesn’t work:
https://vaporlibre.com/sitemap.xml
neither is it
https://vaporlibre.com/sitemap_index.xml
In these urls I am redirected to my home page.
Only this works: https://vaporlibre.com/?sitemap=1
But google doesn’t want it, it tells me that the sitemaps have html tags.
You can’t submit last URL because it includes sub-sitemaps which are redirecting to front page. It could be reason why google detect sitemaps as html.
You should use previous procedure for check conflict to detect from where redirects coming. If you can then upload redirect.php (from previous comment) to plugins directory, activate this plugin and check network tab in browner console. I’m pretty sure that redirects are in WP (based on HTTP headers).
Thread Starter
Javier
(@vaporlibre)
I can’t find it, how can I detect the origin of the redirects?
You can use the plugin https://github.com/stracker-phil/wp-debug-redirect to debug redirects. After activate this plugin, you will find debug stack-trace in HTTP headers. Other way is plugin conflict check.
Based on current HTTP headers, it seems that sitemaps are redirecting by standard WP functions and I think that you can find it with wp-debug-redirect.
It’s possible that you can add rewrite rules in .htaccess – https://yoast.com/help/xml-sitemaps-apache/. It may work because redirects are doing in later phase…
Plugin Support
Jerlyn
(@jerparx)
Closed. No further questions.
Viewing 15 replies — 1 through 15 (of 15 total)
Viewing 15 replies — 1 through 15 (of 15 total)
Can you first confirm that the XML Sitemaps feature is enabled in the pugin In order to enable sitemaps in the Yoast SEO plugin, you would need to perform the following actions:
-
In WordPress go to SEO>General>Features
Toggle the ‘XML Sitemaps’ option to ‘On’
Click ‘Save Changes’
If you have confirmed that sitemaps are enabled and you are still receiving a 404 error at sitemap_index.xml, the error can be caused by a number of issues, including the permalinks or rewrite rules. We would first recommend to try resetting the permalink structure in WordPress which can be done by performing the following steps:
-
In WordPress, go to Settings>Permalinks
Clicking ‘Save Changes’ without making any modifications
We also have additional information regarding the sitemap files creating an error here: https://kb.yoast.com/kb/my-sitemap-index-is-giving-a-404-error-what-should-i-do/
If you continue to receive the error after resetting the permalinks, we would then also suggest adding a set of rewrite rules to your server and we have a guide on adding these for an Apache servers here: https://kb.yoast.com/kb/xml-sitemaps-apache/ and for Nginx servers here: https://kb.yoast.com/kb/xml-sitemaps-nginx/.
Thread Starter
Javier
(@vaporlibre)
I did all the steps, but the same thing still happens to me, It doesn’t give me a 404 error, it simply redirects me to my homepage, what can I do?
- This reply was modified 2 years, 10 months ago by
Javier.
Hi,
We can see that the redirect from the Yoast sitemaps https://vaporlibre.com/sitemap_index.xml to the homepage is coming from the server. We suggest contacting your host provider and verifying that the server is correctly configured and no rules exist which are resulting in that behavior.
Thread Starter
Javier
(@vaporlibre)
I checked the entire server, hired an informatic, I also talked to the administrators of the server and everything is correct, they say it is a plugin problem, reading in the forums I have seen that this happens to many people too.
Hi,
We are not sure why the Yoast sitemaps are failing to appear. But it now sounds like a plugin or theme conflict. Can you try and gather as much information for us as possible? Please perform the following:
1. Make sure you are using the most recent WordPress Core, v5.3.2. If you are not sure what version you have or how to update, your host provider can help. Also, be sure to update your Yoast to v13.2 and update your non-Yoast plugins.
2. Please Check for conflicts.
If there is a conflict with a plugin or a theme, you can create a new GitHub issue for our developers. Please report the issue to a third party developer as well.
If you didn’t find any conflicts or errors, we think the issue is specific to your site. We’d need to investigate further but are unable to do so on these forums. You can purchase Yoast SEO Premium and receive our Premium email support and we can help you further.
Thread Starter
Javier
(@vaporlibre)
I checked all that he told me, nothing works. Previously it worked correctly, it was in an update when it stopped working.
How do you want me to buy the premium version, if the free one doesn’t work?
Yoast SEO sitemaps can be loaded using two URLs, the pretty permalink one and a non-pretty permalink.
Pretty Permalink: https://www.example.com/sitemap_index.xml
Non-Pretty Permalink: https://www.example.com/?sitemap=1
The pretty permalink redirects to the homepage. Please check any redirect plugins you may have and remove redirects that are causing this redirect.
The non-pretty permalink returns an error XML declaration allowed only at the start of the document. Multiple blank line appear in the source code of the sitemap and is due to a conflict with something in your setup. Usually, there is an empty space or a blank line before or after the closing PHP opening or closing tag, which shouldn’t be there.
You can narrow down the exact source of conflict by performing a conflict check. Once you have identified whether your theme or a plugin causes the issue, please contact the developers of that theme or plugin for assistance in finding and removing the whitespace.
Test this on your development or staging site, if you have one. If not, we recommend using the Health Check & Troubleshooting plugin. This plugin allows you to run a conflict check without affecting normal visitors to your site.
As we can imagine that you’re unfamiliar with checking for conflicts, we’d like to point you to a step-by-step guide that will walk you through the process: How to check for plugin conflicts.
All URLs which end with ‘xml’ redirect to front page:
$ curl -i https://vaporlibre.com/sitemapblablablablaxml
HTTP/1.1 301 Moved Permanently
Server: nginx
...
X-Powered-By: PHP/7.3.15
X-Redirect-By: WordPress
...
If you can’t find PHP code or a plugin then you can try to use https://github.com/stracker-phil/wp-debug-redirect. It’ll show debug trace in HTTP headers.
Other issue is white-space:
$ curl -i https://vaporlibre.com/?sitemap=1
HTTP/1.1 200 OK
Server: nginx
Content-Type: text/xml; charset=UTF-8
...
X-Powered-By: PleskLin
<?xml version="1.0" ...
There are 4 empty lines before the content. You should find them into the code or plugins. I think that the theme isn’t source of the white-space.
Thread Starter
Javier
(@vaporlibre)
How can I remove those 4 blanks, I have reviewed all the plugins, and all the files in my root, but nothing.
The problem is that the document is not created on my server to modify it.
I still see redirects…
Yoast SEO generates sitemaps “on the fly” and there aren’t physical XML files. You can’t just open XML file and remove lines.
Empty lines in PHP files can be located anywhere (even on the end of files). Common places are wp-config.php and functions.php.
You should try https://yoast.com/help/how-to-check-for-plugin-conflicts/ You should open two tabs (admin dashboard and sitemap) in the browser. At second tab (sitemap) try to force refresh (ctrl-f5) at each activation/deactivation of plugin.
If you aren’t familiar with this process then you can see video – https://givewp.com/documentation/resources/troubleshoot-wordpress-websites-health-check/
Thread Starter
Javier
(@vaporlibre)
I managed to remove all the spaces, now the file is seen correctly.
But I have another problem, it tells me that the file has html tag.
And the url doesn’t work:
https://vaporlibre.com/sitemap.xml
neither is it
https://vaporlibre.com/sitemap_index.xml
In these urls I am redirected to my home page.
Only this works: https://vaporlibre.com/?sitemap=1
But google doesn’t want it, it tells me that the sitemaps have html tags.
You can’t submit last URL because it includes sub-sitemaps which are redirecting to front page. It could be reason why google detect sitemaps as html.
You should use previous procedure for check conflict to detect from where redirects coming. If you can then upload redirect.php (from previous comment) to plugins directory, activate this plugin and check network tab in browner console. I’m pretty sure that redirects are in WP (based on HTTP headers).
Thread Starter
Javier
(@vaporlibre)
I can’t find it, how can I detect the origin of the redirects?
You can use the plugin https://github.com/stracker-phil/wp-debug-redirect to debug redirects. After activate this plugin, you will find debug stack-trace in HTTP headers. Other way is plugin conflict check.
Based on current HTTP headers, it seems that sitemaps are redirecting by standard WP functions and I think that you can find it with wp-debug-redirect.
It’s possible that you can add rewrite rules in .htaccess – https://yoast.com/help/xml-sitemaps-apache/. It may work because redirects are doing in later phase…
Plugin Support
Jerlyn
(@jerparx)
Closed. No further questions.
Viewing 15 replies — 1 through 15 (of 15 total)
При анализе сайтов в Яндекс.Вебмастере который раз получаем вот такое предупреждение:
При этом при детальном рассмотрении ошибка становится просто предупреждением, не влияющим на индексацию:
Ситуация проясняется, Яндекс не понимает дополнение image, которое присутствует в XML Sitemap.
Лирическое отступление. Вообще-то это обычный косяк Яндекса! Само слово XML (eXtensible Markup Language — расширяемый язык разметки) изначально предполагает любые и произвольные расширения в разметке, при условии, что они делаются в другом пространстве имен. Однако разработчики Яндекса о пространствах имен XML имеют такое же представление, как слушательницы хореографических курсов о мелиорации Узбекистана.
На большинстве наших сайтов XML Sitemap генерируется плагином Yoast SEO, который решает наши задачи более чем полно, и менять его из-за тупой ошибки обработки Яндекса нам не хотелось бы. Поэтому мы попытались найти иное решение.
И решение было найдено. Yoast SEO, как и большая часть плагинов и дополнений к WordPress сделан с учетом архитектуры WP, то есть использует хуки WordPress, что позволяет нам контролировать поведение плагина, не вмешиваясь в программный код (вот за что мы любим WordPress). Был найден фильтр wpseo_xml_sitemap_img_src, который отвечает за формирование URL изображения и мы на него повесили простой обработчик в functions.php:
// Уберем из карты сайта URL картинок
add_filter( 'wpseo_xml_sitemap_img_src', 'remove_image_url' );
function remove_image_url( $uri ) {
return '';
}
Всё! Ссылок на изображения в XML Sitemap WordPress больше нет.
Update. Тут предложили еще более простое решение:
/* Remove Images From Yoast Sitemap */
add_filter( 'wpseo_xml_sitemap_img', '__return_false' );
Update 2. Написал небольшой плагин, который это делает. Получить его бесплатно можно здесь. Если не хотите возится с настройкой темы, просто установите и активируйте этот плагин.
Update 3. июль 2017. Исправил плагин, сейчас он отключает кэш карт сайта в SEO Yoast, и явно фильтрует по регулярным выражениям элементы, которые не нравятся Яндексу. Скачиваем свежую версию плагина.
Update 4. апрель 2019. Доработали плагин. Теперь он еще и правильно канонизирует пагинацию архивов. Подробности позже.
Надеюсь, этот простой рецепт вам поможет.
Перейти к содержимому

В этой небольшой записи, я бы хотел рассказать вам как исправить распространенную ошибку от плагина Yoast SEO.
Есть три основных решения этой ошибки:
- Зайдите в «Настройки» -> «Постоянные ссылки» и нажмите «Сохранить изменения». Иногда WordPress не сразу обновляет ссылки, поэтому этот простой способ может помочь обновить все ссылки на сайте.
- Проверьте наличие записей, тегов или категорий на вашем сайте. Если у вас их нет, то этот может повлечь за собой 404 ошибку. Так же зайдите в «SEO» -> «XML Карта Сайта» -> и проверьте в поле «Функциональность XML-карты сайта» должно быть «Enabled». Если нет, то выберите «Enabled» и сохраните изменения.
- Это решение описано ниже, но оно различается исходя из того на чём работает ваш сайт (Apache или Nginx).
Apache
Для Apache вам нужно добавить код, который написан ниже. Его нужно добавить в .htaccess файл в корне вашего сайта. Самое главное напишите это перед всем другим кодом, который там есть.
# 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?xsl=$1 [L] # END Yoast SEO - XML Sitemap Rewrite Fix
Nginx
Для Nginx решение следующее:
#Yoast sitemap
location ~ ([^/]*)sitemap(.*).x(m|s)l$ {
## this redirects 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?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;
## The following lines are optional for the premium extensions
## News SEO
rewrite ^/news-sitemap.xml$ /index.php?sitemap=wpseo_news last;
## Local SEO
rewrite ^/locations.kml$ /index.php?sitemap=wpseo_local_kml last;
rewrite ^/geo-sitemap.xml$ /index.php?sitemap=wpseo_local last;
## Video SEO
rewrite ^/video-sitemap.xsl$ /index.php?xsl=video last;
}
Если у вас сервер, то вы так же можете перезапустить Nginx сервис — sudo service nginx restart и потом посмотреть изменения.
Послесловие
Если у вас до сих пор показывается ошибка, то вы можете написать под этой записью и я вам постараюсь помочь. А в целом, одно из решений выше вам точно должно помочь, так как других причин для появления 404 ошибки нет.
Источник
- Yoast официальная статья
Об авторе
Ошибка 404 в карте сайта, в основном означает, что карта сайта не существует по целому ряду причин которые решаются следующими способами:
- Сброс структуры ссылок – распространенный способоб решения проблемы с ошибкой 404. Переходим в Admin панель > Настройки> Постоянные ссылки и нажимаем кнопку сохранить, не изменяя ничего. ( Мне помог данный способ )
- Убедитесь , что записи или страницы существуют для того, чтобы создать карту сайта.
Чтобы сделать карту сайта в плагине yoast достаточно перейти в SEO -> XML карта сайта и нажать сохранить изменения.
yoast seo – создание карты сайта
Если вы при переходе по ссылке карты, видите белый экран, то это особенность хостинга, обычно, проблем с яндексом и гуглом не возникает. Они такую карту видят.
Проверить карту можно исходным кодом.
Адрес карты будет site.ru/sitemap_index.xml
Обязательно укажите его в robots.txt
Перейти к содержимому

В этой небольшой записи, я бы хотел рассказать вам как исправить распространенную ошибку от плагина Yoast SEO.
Есть три основных решения этой ошибки:
- Зайдите в «Настройки» -> «Постоянные ссылки» и нажмите «Сохранить изменения». Иногда WordPress не сразу обновляет ссылки, поэтому этот простой способ может помочь обновить все ссылки на сайте.
- Проверьте наличие записей, тегов или категорий на вашем сайте. Если у вас их нет, то этот может повлечь за собой 404 ошибку. Так же зайдите в «SEO» -> «XML Карта Сайта» -> и проверьте в поле «Функциональность XML-карты сайта» должно быть «Enabled». Если нет, то выберите «Enabled» и сохраните изменения.
- Это решение описано ниже, но оно различается исходя из того на чём работает ваш сайт (Apache или Nginx).
Apache
Для Apache вам нужно добавить код, который написан ниже. Его нужно добавить в .htaccess файл в корне вашего сайта. Самое главное напишите это перед всем другим кодом, который там есть.
# 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?xsl=$1 [L] # END Yoast SEO - XML Sitemap Rewrite Fix
Nginx
Для Nginx решение следующее:
#Yoast sitemap
location ~ ([^/]*)sitemap(.*).x(m|s)l$ {
## this redirects 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?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;
## The following lines are optional for the premium extensions
## News SEO
rewrite ^/news-sitemap.xml$ /index.php?sitemap=wpseo_news last;
## Local SEO
rewrite ^/locations.kml$ /index.php?sitemap=wpseo_local_kml last;
rewrite ^/geo-sitemap.xml$ /index.php?sitemap=wpseo_local last;
## Video SEO
rewrite ^/video-sitemap.xsl$ /index.php?xsl=video last;
}
Если у вас сервер, то вы так же можете перезапустить Nginx сервис — sudo service nginx restart и потом посмотреть изменения.
Послесловие
Если у вас до сих пор показывается ошибка, то вы можете написать под этой записью и я вам постараюсь помочь. А в целом, одно из решений выше вам точно должно помочь, так как других причин для появления 404 ошибки нет.
Источник
- Yoast официальная статья
Об авторе
Cправка — Search Console
Войти
Справка Google
- Справочный центр
- Сообщество
- Search Console
- Политика конфиденциальности
- Условия предоставления услуг
- Отправить отзыв
Тема отзыва
Информация в текущем разделе Справочного центра
Общие впечатления о Справочном центре Google
- Справочный центр
- Сообщество
Search Console
Последнее обновление Дек 11, 2020

После переноса моего блога на WordPress в Nginx на Digital Ocean мне пришлось решить несколько проблем, одной из которых была пустая проблема с картой сайта Yoast SEO. Как и большинство блоггеров, я использую плагин Yoast для WordPress SEO, который устраняет необходимость в некоторых других плагинах для нестраничных SEO-функций. Одной из таких функций является генерация XML-карты сайта. Проблема пустого файла Sitemap Yoast отличается от ошибки Sitemap 404, которая встречается чаще. В моем случае страница XML-карты сайта была пустой, на ней ничего не было. Если вы пришли сюда, пытаясь найти ответ на пустую проблему с картой сайта Yoast, то читайте дальше. [ Читать: 5 ошибок в блогах, которые я сделал, когда начал этот блог ]
Yoast SEO Карта сайта Пустая проблема
Картинки ниже описывают проблему. Как видите, файл sitemap.xml, сгенерированный плагином Yoast для WordPress SEO, пуст. Если карта сайта не работает, это может привести к проблемам с правильной или своевременной индексацией вашего сайта Google.
WordPress Yoast SEO Пустой Карта сайта
Когда я отключил W3 Total Cache, я мог видеть отдельные ссылки на карту сайта, но они не были отформатированы и не были связаны. Визуально это было проблемой. [ Читать: Исправить пустую страницу WordPress со словом «ошибка» ]
WordPress Yoast XML Sitemap – без стиля
Когда я просмотрел исходный код HTML карты сайта, он не был пустым и имел то, что должен был иметь. И когда я проверял карту сайта с некоторыми валидаторами карты сайта, я не обнаружил никаких проблем. Так что проблема была только визуальной.
Yoast XML Sitemap Source
Но я все равно хотел исправить эту пустую проблему с картой сайта Yoast XML. Итак, вот что я сделал, чтобы карты сайта WordPress SEO нормально работали на веб-сервере Nginx.
Рекомендуемые руководства:
Исправлена проблема с пустым XML-файлом Yoast
Плагин WordPress SEO после активации предоставляет вам правила перезаписи для веб-сервера Nginx. Но необходимы дополнительные правила переписывания, чтобы сделать генерацию карты сайта XML частью плагина полностью работающей. Пустая карта сайта XML связана с тем, что main-sitemap.xsl(таблица стилей XML) перенаправлена неправильно. Это легко решается добавлением следующего правила перезаписи в файл хоста Nginx внутри блоков сервера:
rewrite ^/([a-z]+)?-?sitemap.xsl$ /index.php?xsl=$1 last;
Если вы заинтересованы в том, чтобы увидеть все правила перезаписи Nginx, которые я использую для корректной работы плагина WordPress SEO, взгляните на блок кода ниже:
# This rewrite redirects sitemap.xml to sitemap_index.xml, which is what Yoast's WordPress SEO plugin generates.
rewrite ^/sitemap.xml$ /sitemap_index.xml permanent;
# This rewrite ensures that the styles are available for styling the generated sitemap.
rewrite ^/([a-z]+)?-?sitemap.xsl$ /index.php?xsl=$1 last;
# These rewrites rule are generated by Yoast's plugin for Nginx webserver.
rewrite ^/sitemap_index.xml$ /index.php?sitemap=1 last;
rewrite ^/([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;
Я загрузил этот код в мой Gist-репозиторий на тот случай, если вы захотите его разветвить или улучшить. [ Читать: 6 настроек FeedBurner для улучшения доставки вашего WordPress ]
Настройки общего кэша W3 для предотвращения пустого файла Sitemap Yoast
В дополнение к перезаписи Nginx для исправления пустой ошибки Yoast SEO Sitemap вам также необходимо правильно настроить общий кэш W3 и применить необходимые исключения, чтобы избежать кэширования или минимизации карты сайта и связанных файлов. Добавьте следующий код в кэш страницы (никогда не кэшируйте следующие элементы), Minify (никогда не минимизируйте следующие элементы), кэш браузера (список исключений 404 ошибок) и CDN (отклоненные файлы) общего кэша W3.
([a-z0-9_-]+)?sitemap(_index)?(-)?([0-9]*)?.(xml(.gz)?|xsl)$
Приведенный выше код также доступен в моем репозитории Gist для доработки. Вот скриншот того, куда должна идти приведенная выше строка кода в настройках W3 Total Cache.
W3 Total Cache Settings для Yoast XML Sitemap на Nginx
После того как вы ввели свои правила перезаписи и добавили необходимые настройки в конфигурацию общего кэша W3, продолжайте, перезапустите веб-сервер Nginx и очистите все кэши. Это должно было решить вашу пустую проблему с картой сайта Yoast SEO .
Источник записи: https://www.smarthomebeginner.com
Недавно один из моих клиентов пришёл ко мне с такой проблемой: карта сайта, которая генерируется плагином Yoast SEO ломается на их огромном высоконагруженном WordPress сайте.
Yoast SEO разбивает карту сайта на несколько отдельных кусков. На этом сайте отдельные куски успешно создаются, а вот общий индексный файл — нет, скрипту просто не хватает времени на все эти операции. Это влечёт за собой другую проблему — поисковые системы не видят карту сайта.
Карта сайт реально помогает поисковым системам находить новый контент на вашем сайте, поэтому исправление данного бага стало приоритетной задачей для клиента. Ошибка плавающая, поэтому трудно поддаётся диагностике, а на других сайтах всё работает как часы.
Учитывая, что сайт имеет десятилетний опыт, можно легко предположить, почему карта сайт ломается: из-за огромного количества записей сервер шлёт скрипт далеко и надолго, потому что тот не успевает выполнить свои задачи за отведённые ему 30 секунд.
Увеличиваем таймаут до 120 секунд — всё плохо.
Увеличиваем таймаут до 300 секунд. Пять грёбаных минут, Карл!
Стало немного получше.
Если и дальше увеличивать таймаут, то это чревато тем, что сервер рано или поздно ляжет совсем.
Решение
Yoast SEO не имеет (пока) WP-CLI (WordPress command line interface) команд, но мы же можем использовать wp eval для запуска произвольного PHP кода в инфраструктуре WordPress.
После глубокого анализа исходного кода плагина Yoast SEO был найден PHP класс и его методы для вывода индексной карты сайта (та, что содержит ссылки на другие карты).
Пробуем запусить процесс через wp eval:
wp eval ' $sm = new WPSEO_Sitemaps; $sm->build_root_map(); $sm->output(); '
Выполнение задачи заняло небольшое количество времени и индексный файл был успешно получен. Значит, мы пошли правильным путём.
Теперь вешаем всё это добро на крон с выводом результата в статический файл:
0 3 * * * cd /srv/www/example.com && /usr/local/bin/wp eval '$sm = new WPSEO_Sitemaps;$sm->build_root_map();$sm->output();' > /srv/www/example.com/wp-content/uploads/sitemap_index.xml
Финальным шагом меняем конфигурацию веб-сервера Nginx таким образом, чтобы ботам, которые пытаются получить файл sitemap_index.xml в корне сайта, отдавалась его статическая версия из папки uploads, куда его кладёт наш крон:
location ~ ([^/]*)sitemap(.*).x(m|s)l$ {
rewrite ^/sitemap.xml$ /sitemap_index.xml permanent;
rewrite ^/([a-z]+)?-?sitemap.xsl$ /index.php?xsl=$1 last;
rewrite ^/sitemap_index.xml$ /wp-content/uploads/sitemap_index.xml last;
rewrite ^/([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;
}
Теперь роботы поисковых систем рады, так как им больше не нужно ждать по 5 минут завершения процесса генерации карты сайта, а сам сайт не прикладывается поспать в это время, так как крон запускает скрипт в отдельном PHP процессе пактически без ограничений.
А клиент счастлив, что ему нет необходимости менять SEO плагин и его бизнес спасён.
Отдельная благодарность WP-CLI за чуточку магии.
Ссылки
- How I fixed Yoast SEO sitemaps on a large WordPress site
Cron seo WordPress Yoast Производительность
При анализе сайтов в Яндекс.Вебмастере который раз получаем вот такое предупреждение:
При этом при детальном рассмотрении ошибка становится просто предупреждением, не влияющим на индексацию:
Ситуация проясняется, Яндекс не понимает дополнение image, которое присутствует в XML Sitemap.
Лирическое отступление. Вообще-то это обычный косяк Яндекса! Само слово XML (eXtensible Markup Language — расширяемый язык разметки) изначально предполагает любые и произвольные расширения в разметке, при условии, что они делаются в другом пространстве имен. Однако разработчики Яндекса о пространствах имен XML имеют такое же представление, как слушательницы хореографических курсов о мелиорации Узбекистана.
На большинстве наших сайтов XML Sitemap генерируется плагином Yoast SEO, который решает наши задачи более чем полно, и менять его из-за тупой ошибки обработки Яндекса нам не хотелось бы. Поэтому мы попытались найти иное решение.
И решение было найдено. Yoast SEO, как и большая часть плагинов и дополнений к WordPress сделан с учетом архитектуры WP, то есть использует хуки WordPress, что позволяет нам контролировать поведение плагина, не вмешиваясь в программный код (вот за что мы любим WordPress). Был найден фильтр wpseo_xml_sitemap_img_src, который отвечает за формирование URL изображения и мы на него повесили простой обработчик в functions.php:
// Уберем из карты сайта URL картинок
add_filter( 'wpseo_xml_sitemap_img_src', 'remove_image_url' );
function remove_image_url( $uri ) {
return '';
}
Всё! Ссылок на изображения в XML Sitemap WordPress больше нет.
Update. Тут предложили еще более простое решение:
/* Remove Images From Yoast Sitemap */
add_filter( 'wpseo_xml_sitemap_img', '__return_false' );
Update 2. Написал небольшой плагин, который это делает. Получить его бесплатно можно здесь. Если не хотите возится с настройкой темы, просто установите и активируйте этот плагин.
Update 3. июль 2017. Исправил плагин, сейчас он отключает кэш карт сайта в SEO Yoast, и явно фильтрует по регулярным выражениям элементы, которые не нравятся Яндексу. Скачиваем свежую версию плагина.
Update 4. апрель 2019. Доработали плагин. Теперь он еще и правильно канонизирует пагинацию архивов. Подробности позже.
Надеюсь, этот простой рецепт вам поможет.
Будучи загружен более 1 миллиона раз, плагин WordPress SEO плагин на сегодняшний день является лучшим и наиболее полным SEO плагином для WordPress. В то время как он не дал нам никаких проблем в прошлом, для некоторых пользователей это была боль. Недавно один из наших клиентов столкнулся с вопросом о получении ошибки 404 для своих карт сайта порожденных плагином WordPress SEO от Yoast. После нескольких попыток, нам удалось выяснить решение. В этой статье мы покажем вам, как исправить ошибку 404 в карте сайта плагина WordPress SEO от Yoast.
ВАЖНО!
Очень важно, чтобы вы поняли, что эта проблема, скорее всего, вызвана плохо кодированной функцией темы или плагина. плагин Йоаст прекрасно работает на наших сайтах. Просто хотел быть очень ясно говорит об этом.
Первое, что вы должны сделать, это открыть файл .htaccess (вы можете сделать это с помощью плагина WordPress SEO > Возможность редактирования файлов) и просто добавьте следующий код там:
# WordPress SEO - XML Sitemap исправление <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^sitemap_index.xml$ /index.php?sitemap=1 [L] RewriteRule ^([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 [L] </IfModule> # конец WordPress SEO - XML Sitemap исправление
Для большинства людей это исправило проблему. Кто-то сообщил, что в то время как этот код фиксируется проблему, страница все еще посылала заголовок ответа 404, что означало, что инструмент Google Вебмастера не мог найти её. Ну в случае нашего клиента, указанное решение не решило проблему.
В то время как это не является предпочтительным, у нас не было выбора, кроме как изменить файлы ядра плагина, чтобы исправить эту проблему. Отредактировали class-sitemaps.php, расположенный в «/wp-content/plugins/wordpress-seo/inc/class-sitemaps.php».
Вы должны смотреть на код функции init() и сделать этот раздел выглядеть следующим образом:
01/**
02 * Initialize sitemaps. Add sitemap rewrite rules and query var
03 */04 function init() {
05 global $wp_rewrite;
06 $GLOBALS['wp']->add_query_var( 'sitemap' );
07 $GLOBALS['wp']->add_query_var( 'sitemap_n' );
08 add_rewrite_rule( 'sitemap_index.xml$', 'index.php?sitemap=1', 'top' );
09 add_rewrite_rule( '([^/]+?)-sitemap([0-9]+)?.xml$','index.php?sitemap=$matches[1]&sitemap_n=$matches[2]', 'top' );
10 $wp_rewrite->flush_rules();
11 }
В основном то, что мы делаем, это добавляем глобальной $ wp_rewrite и добавление flush_rules после кода. При добавлении этого в плагин, это, кажется, должно исправить 404 на веб-сайте нашего клиента.Мы понятия не имеем, почему Yoast не делает это по умолчанию, Но мне кажется, что довольно много пользователей, имеющих эту проблему 404 сайта.
Обновление: Как некоторые из наших пользователей сообщили , что после применения исправления выше, они по- прежнему снимают флажок в карты сайта плагина SEO от Yoast и сохранить свои настройки. После этой повторной проверки вариант карты сайта ошибка для них была исправлена.
Если у Вас есть эта проблема, мы надеемся, что это исправление помогло вам.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
На одном из своих блогов, решил поставить, это, сейчас популярный и на самом деле очень хороший плагин: WordPress SEO от Yoast Team. И Вы знаете, он на самом деле хорош! Да, может не такой понятный как All In One SEO Pack, но во многом лучше него. Допустим, он может убирать эту не нужную категорию /category/ или заменить её на что-то иное. Так же, очень круто, что он сам добавляет к названиям URL страниц расширение .html! И он сам создает xml sitemap, но вот тут у меня не все так радужно получилось.
Казалось бы, что проще, есть функция, есть кнопочка, жми её, заходи на страницу карты сайта и добавляй этот адрес в Google и Яндекс. Но! Как оказалось при переходе на страницу xml-sitemap она выдавала ошибку 404! Что за дела?
Обновлено! Читать перед редактированием!
В комментариях к данному посту, пользователь kamar87 предложил очень простой и как оказалось реально действующий способ избавиться от данной проблемы без каких либо редактирований файлов! Вот его дословная цитата:
Ещё рабочий вариант без всяких редактирований файла!
Поле того как поставили галочку на «Отметьте этот пункт, чтобы включить XML карту сайта.» — сохраняем настройки. Переходим Настройки-Постоянные ссылки и просто нажимаем сохранить. Все!
По дальнейшим отзывам, всё на самом деле так просто! Поэтому выражаем ему благодарность и дальше пост НЕ читаем ?
А для тех кто всё-таки хочет заморочиться, продолжим…
Как я понял, проблема как раз в конфликте карты сайта и настройки расширений .html
Как исправить ошибку 404 в sitemaps от YOAST SEO?
Первое что мы должны сделать, это зайти в наш .htaccess и добавить следующий код:
# WordPress 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?xsl=$1 [L]
# END WordPress SEO — XML Sitemap Rewrite Fix
Обычно этого достаточно, но смотрите, зачастую первые строки уже есть в вашем .htaccess файле. Поэтому достаточно добавить строки:
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?xsl=$1 [L]
К уже существующему коду. А если у вас там есть строка: /IfModule, то код должен быть перед ней.
Если же при изменении .htaccess файл sitemap так же выдает ошибку 404, то надо лезть в код самого плагина и добавить там пару строк.
Заходим в:
/wp-content/plugins/wordpress-seo/inc/class-sitemaps.php
и где-то на 80 строке, перед строками:
/**
* Class constructor
*/
Вставляем следующий код:
/**
* Initialize sitemaps. Add sitemap rewrite rules and query var
*/
function init() {
global $wp_rewrite;
$GLOBALS[‘wp’]->add_query_var( ‘sitemap’ );
$GLOBALS[‘wp’]->add_query_var( ‘sitemap_n’ );
add_rewrite_rule( ‘sitemap_index.xml$’, ‘index.php?sitemap=1’, ‘top’ );
add_rewrite_rule( ‘([^/]+?)-sitemap([0-9]+)?.xml$’, ‘index.php?sitemap=$matches[1]&sitemap_n=$matches[2]’, ‘top’ );
$wp_rewrite->flush_rules();
}
Теперь, всё точно должно заработать!





![[Решено] WordPress Yoast SEO карта сайта пуста на Nginx](https://mediadoma.com/wp-content/uploads/2020/06/post-20553-5ef3ec0c106b7.jpg)
![[Решено] WordPress Yoast SEO карта сайта пуста на Nginx](https://mediadoma.com/wp-content/uploads/2020/06/post-20553-5ef3ec0caeb88.jpg)
![[Решено] WordPress Yoast SEO карта сайта пуста на Nginx](https://mediadoma.com/wp-content/uploads/2020/06/post-20553-5ef3ec0d71929.jpg)
![[Решено] WordPress Yoast SEO карта сайта пуста на Nginx](https://mediadoma.com/wp-content/uploads/2020/06/post-20553-5ef3ec0e5bd6e.jpg)

