Nginx ошибка 410

Understand the HTTP 410 Gone Error code: What are the causes, and solutions, and why we sometimes intentionally use this error response in SEO.

Table of Contents

  • What is the 410 Gone error?
    • 410 error messages
  • 410 Bad Gateway? No way!
  • 410 Gone vs 404 Not Found
  • 410 Gone vs 404 Not Found for SEO
  • Solving the 410 Gone
  • How to create 410 errors for no longer existing pages?
    • How to configure the 410 error with Apache

      • Redirect to the 410 error page with the Apache mod_alias module:
      • Redirect to 410 error pages with the Apache mod_rewrite module
    • How to configure the 410 error with Nginx
    • How to show the 410 error with PHP code
  • All HTTP Status Codes

What is the 410 Gone error?

The HTTP 410 Gone Client Error is a response code that indicates that requested resource is no longer accessible and that this condition is likely to be permanent.

This is an error message that is usually used to explicitly indicate that a certain resource or page is no longer available.

410 error messages

Depending on the web server or browser you may find different descriptive messages for this error:

  • “HTTP Status 410”
  • “410 Gone”
  • “This page can’t be found -It may have been moved or deleted. HTTP ERROR 410”
  • “ERROR 410”
  • A Blank page, e.g. Firefox Browser.

For example, in Brave browser (based on the Chromium web browser), you’ll likely see a paper icon along with a simple message telling you “This web.domain page can't be found“:

Different 410 error messages depending on the server and browser

Default php 410 error message displayed in a Chromium browser

The default 410 Gone error displayed by Apache, looks like this:

Apache 410 gone error

410 Gone, Apache default page error

410 Bad Gateway? No way!

There is no confusion here: 410 Gone is HTTP 410 Gone, nothing else.

If you happen to find information or questions relating http status 410 with the wrong description Bad Gateway instead of Gone, it will be most probably adressed to IT people managing Chrome devices, nothing to do with HTTP status codes!

Google states immediatly the resemblance between HTTP Status Codes and those codes provided by Chrome device related managing. Literally reads “The error codes have similar patterns to HTTP error codes”. According to their own status codes, 410 will mean “Device not found”: Quite another world.

HTTP 410 is not Bad Gateway. Follow the link to our article to fully understand 502 Bad Gateway.

410 Gone vs 404 Not Found

The “410 Gone” error can be confused with the “404 Not Found” error. Both error codes are used to communicate that the requested page or resource is not available.

The difference is subtle: The 410 Gone Error means “permanently not available” while the 404 Not Found means “temporarily not available”.

A common situation in which we encounter the 404 error is when we try to access a misspelled URL.

One use case where the HTTP 410 code is helpful is that of a malware infection. The malware may have published URLs with words in search engines that can damage our reputation. Showing a 410 is a way to indicate to crawlers that we do not have that content.

410 Gone vs 404 Not Found for SEO

When Google crawls your website to index your pages, it will treat each page or resource differently depending on the HTTP code returned by the server.

In a Webmaster Hangout, Google’s John Mueller explained the difference:

The subtle difference here is that a 410 will sometimes fall out a little faster than a 404. But usually, we’re talking on the order of a couple days or so.

John Mueller, Senior Webmaster Trends Analyst at Google

Here in this Webmaster Hangout, you have the explanation from John Mueller:

Transcription:
– John Muller: “… from our point of view in the mid term, long term 404 is the same as 410, for us. So in both of these cases we drop those URLs from the index … we generally reduce crawling a little bit of those URLs, so that we don’t spend so much time crawling things that we know don’t exist. The subtle difference here is that a 410 will sometimes fall out a little bit faster than a 404. We usually are talking on the order of couple of days.”

Use the 410 Gone Status Code, if you want to speed up the process of Google removing the web page from their index.

Speeding up page removal from a search index can be especially useful after a malware intrusion, where a hacker infects a site with hundreds of spam pages and hideous URLs. Redirecting all those spam pages to a 410 Gone status page will help us speeding up the index deletion.

Why speeding things up to clean up the mess? Not only for safety, authority and plain control on your assets.
At the same time you are saving Googlebot and many other search engine crawlers time and effort, something called crawl budget. Remember this.

You want to treasure your crawl budget to let the bots use it at full power on your best competing contents.

Whatever Google voice said, former malware URLs can be a long term go-and-try for the bots, ending up in repeating 404 errors diminishing your crawl budget. You better 410 those rogue URLs and let bots understand faster what happens.

Remember: 404 looks like an accident, an error, a red light on the dashboard. 410 is fully intentioned. Use it.

Solving the 410 Gone

The 410 Error uses to be an intentional error code. Webmasters use it to declare that a resource is no longer available, so we can consider that it is not a random web error or server configuration error.

Having said that, if you experience a “410 Gone” error:

  1. It’s a good idea to check the link you are trying to visit. If there is no mistake in the URL, then,
  2. Take into account that the website owner might have intentionally removed the content or moved it to a new domain or URL.
  3. A final workaround is to look for the “product”, “service” or “content” by using some keywords on your preferred search engine.

How to create 410 errors for no longer existing pages?

We describe below different methods to help you create 410 errors

How to configure the 410 error with Apache

You can redirect a page to the 410 Gone error using two different modules.

Redirect to the 410 error page with the Apache mod_alias module:

The easiest way to redirect to 410 error pages on Apache servers is to call the default 410 HTTP server response using the “Redirect” directive in your apache.config or .htaccess file:

Redirect gone /path/to/the/page_to_remove

Redirect to 410 error pages with the Apache mod_rewrite module

If you need more sophisticated redirections you can use the RewriteRule of mod_rewrite Apache module.

Reproducing the same previous redirect with a Rewrite command in your your apache.config or .htaccess file:

RewriteEngine On
RewriteRule ^/path/to/the/page_to_remove$ - [L,NC,G]

The flag “G” is the one in charge of showing the “Gone” error.

As mentioned, with this mod_rewrite module you can use regular expressions and target multiple pages at once:

RewriteEngine On
RewriteRule ^/path/to/the/(page_to_remove|page_to_eliminate|also_this_one)\.php$ - [L,NC,G]

How to configure the 410 error with Nginx

If you are working with Nginx, edit you nginx.conf file define a location block to target your single or multiple pages. Reproducing same previous sample URL: /path/to/the/page_to_remove

location = /path/to/the/page_to_remove { 
  return 410; 
}

And you can also take advantage of the regex rules in the location section like any other nginx location configuration. Reproducing previous sample of multiple pages:

location ~ ^/path/to/the/(page_to_remove|page_to_eliminate|also_this_one) { 
  return 410; 
}

At Wetopi we use Nginx for it’s performance, and best part is that you can use your own Free development servers to test configuration changes like the ones exposed in this article.

Save you website: don’t test in production!

When testing new server configurations, it is highly recommended to work on a “localhost” or “Staging” server.

If you don’t have a development WordPress server, signup at wetopi, it’s FREE.

How to show the 410 error with PHP code

If you want to show the “410 Gone” in a PHP page, all you need is to output the 410 header.

Paste the following code at the beginning of the affected page:

<?php
header( "HTTP/1.1 410 Gone" );
exit();

All HTTP Status Codes

200 OK

201 Created

202 Accepted

203 Non-Authoritative Information

204 No Content

205 Reset Content

206 Partial Content

207 Multi-Status

208 Already Reported

226 IM Used

300 Multiple Choices

301 Moved Permanently

302 Found

303 See Other

304 Not Modified

305 Use Proxy

307 Temporary Redirect

308 Permanent Redirect

400 Bad Request

401 Unauthorized

402 Payment Required

403 Forbidden

404 Not Found

405 Method Not Allowed

406 Not Acceptable

407 Proxy Authentication Required

408 Request Timeout

409 Conflict

410 Gone

411 Length Required

412 Precondition Failed

413 Payload Too Large

414 Request-URI Too Long

415 Unsupported Media Type

416 Requested Range Not Satisfiable

417 Expectation Failed

418 I’m A Teapot

421 Misdirected Request

422 Unprocessable Entity

423 Locked

424 Failed Dependency

426 Upgrade Required

428 Precondition Required

429 Too Many Requests

431 Request Header Fields Too Large

444 Connection Closed Without Response

451 Unavailable For Legal Reasons

499 Client Closed Request

We are techies passionate about WordPress. With wetopi, a Managed WordPress Hosting, we want to minimize the friction that every professional faces when working and hosting WordPress projects.

Not a wetopi user?

Free full performance servers for your development and test.
No credit card required.

28 декабря 2017 г. Ошибки HTTP

Ошибка 410 Gone – это код состояния ответа HTTP , указывающий, что ресурс, запрошенный клиент был окончательно удален, и клиенту не следует ожидать альтернативного адреса перенаправления или пересылки. Код 410 Gone может показаться похожим на код 404 Not Found , который мы рассматривали несколько месяцев назад, но эти два кода служат совершенно разным целям. Код 404 указывает, что запрошенный ресурс не в настоящее время доступен, но он может быть доступен в будущих запросах. И наоборот, код 410 является явным указанием на то, что запрошенный ресурс использовался , но с тех пор он был окончательно удален и не будет будут доступны в будущем. Таким образом, код ответа 404 указывает, что пользовательский агент (браузер) может повторять запросы к тому же ресурсу URI , в то время как 410 указывает пользовательскому агенту не повторять запросы к тому же самому ресурсу.

Как и большинство кодов ответов HTTP – особенно те, которые указывают на ошибку – появление 410 Gone Error может быть проблемой при правильной диагностике и решении. С потенциальным пулом из более 50 кодов состояния, которые представляют сложные отношения между клиентом, веб-приложением, веб-сервером и часто несколькими сторонними веб-службами, определяя причину конкретной код состояния может быть проблемой даже в самых лучших обстоятельствах.

В этой статье мы рассмотрим 410 Gone Error более подробно, посмотрев, что может вызвать сообщение, а также несколько советов по диагностике и отладке появления этой ошибки в вашем собственном приложении. Мы даже рассмотрим ряд самых популярных систем управления контентом ( CMS ) на предмет потенциальных проблемных областей, которые могут привести к тому, что ваш собственный веб-сайт будет генерировать ошибку 410 Gone Error неожиданно. Давайте углубимся!

Содержание

  1. На стороне сервера или на стороне клиента?
  2. Начать с тщательного резервного копирования приложения
  3. Диагностика ошибки 410 Gone
  4. Устранение неполадок на стороне клиента
  5. Проверьте запрашиваемый URL
  6. Общая отладка Платформы
  7. Откатить последние обновления
  8. Удаление новых расширений, модулей или подключаемых модулей
  9. Проверить на непредвиденные изменения базы данных
  10. Устранение неполадок на стороне сервера
  11. Подтвердите конфигурацию вашего сервера
  12. Просмотр журналов
  13. Отладка кода или скриптов приложения

На стороне сервера или на стороне клиента?

Все коды состояния ответа HTTP, которые находятся в категории 4xx , являются рассматриваются ответы клиента об ошибках . Эти типы сообщений контрастируют с ошибками в категории 5xx , такими как 504 Gateway Timeout Error , которые мы исследовали некоторое время назад, которые считаются ответы об ошибках сервера . При этом появление ошибки 4xx не обязательно означает, что проблема возникла на стороне клиента, где «клиент» – это веб-браузер или устройство, используемое для доступа к приложению. Часто, если вы пытаетесь диагностировать проблему в собственном приложении, вы можете сразу же игнорировать большую часть клиентского кода и компонентов, таких как HTML, каскадные таблицы стилей (CSS), клиентский JavaScript и т. Д. Это также не относится исключительно к веб-сайтам. Многие приложения для смартфонов с современным пользовательским интерфейсом фактически работают на обычных веб-приложениях за кулисами; тот, который просто скрыт от пользователя.

С другой стороны, это не исключает клиента как фактическую причину Ошибка 410 . Во многих случаях клиент может непреднамеренно отправить запрос не на тот ресурс, что может привести к 410 Gone Error . Мы рассмотрим некоторые из этих сценариев (и возможные решения) ниже, но имейте в виду, что, хотя 410 Gone Error считается ответом на ошибку клиента , это по сути не означает, что мы можем исключить ни клиента, ни сервер как виновников этого сценария. В этих сценариях сервер по-прежнему является сетевым объектом, который создает 410 Gone Error и возвращает его как код ответа HTTP клиенту, но возможно, проблема каким-то образом связана с клиентом.

Начать с тщательного резервного копирования приложения

Как и в любом другом случае, лучше перестраховаться на начало, чем облажаться и пожалеть об этом позже в будущем. Таким образом, критично , чтобы вы выполнили полное резервное копирование вашего приложения, базы данных и т. Д. Перед попыткой каких-либо исправлений или изменений в системе. Еще лучше, если у вас есть такая возможность, создайте полную копию приложения на вторичном промежуточном сервере, который не является «активным» или по другим причинам неактивен и не доступен для всех. Это даст вам чистую площадку для тестирования, на которой можно протестировать все возможные исправления для решения проблемы, не ставя под угрозу безопасность или неприкосновенность вашего действующего приложения.

Диагностика ошибки 410 Gone

Как обсуждалось во введении, ошибка 410 Gone указывает, что пользовательский агент (в большинстве случаев веб-браузер) запросил ресурс, который был окончательно удален из сервер . Это могло произойти при нескольких разных обстоятельствах:

  • Сервер имел доступный действительный ресурс в запрошенном месте, но это было намеренно удалено.
  • Сервер должен иметь допустимый ресурс в запрошенном месте, но он непреднамеренно сообщает, что ресурс был удален.
  • Клиент пытается запросить неверный ресурс.

Устранение неполадок на стороне клиента

Поскольку 410 Gone Error является клиентом код ответа об ошибке , лучше всего начать с устранения любых потенциальных проблем на стороне клиента, которые могут быть причиной этой ошибки. Вот несколько советов, которые можно попробовать в браузере или устройстве, на котором возникают проблемы.

Проверьте запрашиваемый URL

Наиболее частая причина Ошибка 410 Gone просто вводит неверный URL. Как обсуждалось ранее, многие веб-серверы надежно защищены, чтобы запретить доступ к неправильным URL-адресам, к которым сервер не готов предоставить доступ. Это может быть что угодно, от попытки доступа к файловому каталогу через URL-адрес до попытки получить доступ к частной странице, предназначенной для других пользователей. Поскольку коды 410 встречаются не так часто, как коды 404 , появление 410 обычно означает, что запрошенный URL был когда-то действителен, но теперь это не так. В любом случае рекомендуется дважды проверить точный URL-адрес, который возвращает ошибку 410 Gone Error , чтобы убедиться, что это целевой ресурс.

Общая отладка Платформы

Если вы используете общие программные пакеты на сервере, который отвечает 410 Gone Error , вы можете начать с изучения стабильности и функциональность этих платформ в первую очередь. Наиболее распространенные системы управления контентом, такие как WordPress, Joomla! И Drupal, обычно хорошо протестированы сразу после установки, но как только вы начнете вносить изменения в базовые расширения или код PHP ( язык, на котором написаны почти все современные системы управления контентом), слишком легко вызвать непредвиденную проблему, которая приведет к 410 Gone Error .

Ниже приведены несколько советов, которые помогут вам устранить неполадки на некоторых из этих популярных программных платформ.

Откатить последние обновления

Если вы недавно обновляли саму систему управления контентом, незадолго до этого появилась ошибка 410 Gone , вы можете рассмотреть возможность отката к предыдущей версии, которую вы установили, когда все работало нормально. Точно так же любые расширения или модули, которые вы, возможно, недавно обновили, также могут вызвать проблемы на стороне сервера, поэтому возврат к предыдущим версиям также может помочь. Чтобы получить помощь с этой задачей, просто Google «понизьте версию [PLATFORM_NAME]» и следуйте инструкциям. Однако в некоторых случаях некоторые CMS на самом деле не предоставляют возможности понижения версии, что означает, что они считают базовое приложение вместе с каждой новой выпущенной версией чрезвычайно стабильным и свободным от ошибок. Обычно это относится к более популярным платформам, поэтому не бойтесь, если вы не найдете простой способ вернуть платформу к более старой версии..

Удаление новых расширений, модулей или подключаемых модулей

В зависимости от конкретной системы управления контентом, которую использует ваше приложение, точное имя этих компонентов будет другим, но они служат одной и той же цели во всех системах: улучшают возможности и функции платформы сверх того, на что она обычно способна из коробки. Но будьте осторожны: такие расширения могут более или менее полностью контролировать систему и вносить практически любые изменения, будь то код PHP , HTML, CSS, JavaScript или база данных. Таким образом, может быть целесообразно удалить все новые расширения, которые могли быть недавно добавлены. Снова введите в Google имя расширения для официальной документации и помощи в этом процессе.

Проверить на непредвиденные изменения базы данных

Стоит отметить, что даже Если вы удаляете расширение через панель управления CMS, это не гарантирует , что изменения, внесенные расширением, были полностью отменены. Это особенно верно для многих расширений WordPress, которым предоставляется карт-бланш в приложении, включая права полного доступа к базе данных. Если автор расширения явно не кодирует такие вещи, существуют сценарии, в которых расширение может изменять записи базы данных, которые не «принадлежат» самому расширению, а вместо этого создаются и управляются другими расширениями (или даже самой базовой CMS). В этих сценариях расширение может не знать, как отменить изменения в записях базы данных, поэтому оно будет игнорировать такие вещи во время удаления. Диагностировать такие проблемы может быть непросто, но я лично сталкивался с такими сценариями несколько раз, поэтому ваш лучший способ действий, если вы достаточно уверены, что расширение является вероятным виновником 410 Gone Error , заключается в том, чтобы открыть базу данных и вручную просмотреть таблицы и записи, которые, вероятно, были изменены расширением.

Прежде всего, не бойтесь сообщить о своей проблеме в Google. Попробуйте выполнить поиск по конкретным терминам, связанным с вашей проблемой, например по названию CMS вашего приложения, вместе с 410 Gone Error . Скорее всего, вы найдете кого-то, кто столкнулся с той же проблемой.

Устранение неполадок на стороне сервера

Если вы не запускаете приложение CMS – или даже если да, но вы уверены, что 410 Gone Error не связана с этим – вот несколько дополнительных советов, которые помогут вам устранить причину проблемы на стороне сервера вещей.

Подтвердите конфигурацию вашего сервера

Вероятно, ваше приложение работает на сервере, который использует одно из двух самых популярных программных веб-серверов, Apache или nginx . На момент публикации оба этих веб-сервера составляют более 84% мирового программного обеспечения веб-серверов! Таким образом, один из первых шагов, которые вы можете предпринять, чтобы определить, что может быть причиной этих кодов ответа 410 Gone Redirect , – это проверить файлы конфигурации программного обеспечения вашего веб-сервера на предмет непреднамеренных инструкций по перенаправлению.

Чтобы определить, какой веб-сервер использует ваше приложение, вам нужно найти ключевой файл. Если ваш веб-сервер – Apache, поищите файл .htaccess в корневом каталоге файловой системы вашего веб-сайта. Например, если ваше приложение размещено на общем хосте, у вас, скорее всего, будет имя пользователя, связанное с учетной записью хостинга. В таком случае корневой каталог приложения обычно находится по пути /home//public_html/, поэтому файл .htaccess будет быть в /home//public_html/.htaccess .

Если вы нашли файл .htaccess , откройте его в текстовом редакторе и найдите строки, в которых используются директивы RewriteXXX , которые являются частью модуля mod_rewrite в Apache. Подробное описание того, как работают эти правила, выходит далеко за рамки данной статьи, однако основная концепция заключается в том, что директива RewriteCond определяет текстовый шаблон, который будет сопоставляться с введенными URL-адресами. Если соответствующий URL-адрес запрашивается посетителем сайта, директива RewriteRule , следующая за одной или несколькими директивами RewriteCond , используется для выполнения фактического перенаправления запрос на соответствующий URL.

Например, вот простой RewriteRule , который соответствует всем входящим запросам на https://airbrake.io /expired_page и отвечает кодом ошибки 410 Gone Redirect :

  RewriteEngine onRewriteRule ^ (. *) $ https://airbrake.io/expired_page$1 [R = 410, L]  

Обратите внимание на флаг R = 410 в конце RewriteRule , в котором явно указано, что код ответа должен быть 410 , указывая для пользовательских агентов, что ресурс был окончательно удален и не следует делать никаких запросов в будущем. Таким образом, если вы обнаружите какие-либо странные директивы RewriteCond или RewriteRule в файле .htaccess , которые, похоже, не принадлежат попробуйте временно закомментировать их (используя префикс символа # ) и перезапустите веб-сервер, чтобы посмотреть, решит ли это проблему.

С другой стороны, если ваш сервер работает на nginx , вам нужно будет поискать совершенно другой файл конфигурации. По умолчанию этот файл называется nginx.conf и находится в одном из нескольких общих каталогов: /usr/local/nginx/conf , /etc/nginx или /usr/local/etc/nginx . После обнаружения откройте nginx. conf в текстовом редакторе и найдите директивы, использующие флаг кода ответа 410 . Например, вот простая директива блока (то есть именованный набор директив), которая настраивает виртуальный сервер для airbrake.io и гарантирует, что страница ошибки представлен агенту пользователя, который делает запрос 404 Not Found , отправляется на страницу ошибки /deleted.html и получает сообщение 410 Gone ответ с кодом ошибки:

  server {listen 80;  слушайте 443 ssl;  имя_сервера airbrake.io;  error_page 404 = 410/deleted.html;}

Просмотрите файл nginx.conf на предмет аномальных директив или строк, содержащих Флаг 410 . Закомментируйте любые отклонения перед перезапуском сервера, чтобы увидеть, была ли решена проблема.

Параметры конфигурации для каждого типа веб-сервера могут значительно различаться, поэтому мы просто перечислим несколько популярных из них. вам нужно просмотреть некоторые ресурсы в зависимости от того, на каком типе сервера работает ваше приложение:

  • Apache
  • Nginx
  • IIS
  • Node.js
  • Apache Tomcat

Просмотр журналов

Почти каждое веб-приложение в той или иной форме будет вести журналы на стороне сервера. Журналы приложений обычно представляют собой историю того, что приложение делало, например, какие страницы были запрошены, к каким серверам оно подключалось, какие результаты в базе данных предоставляет и т. д. Журналы сервера связаны с фактическим оборудованием, на котором запущено приложение, и часто предоставляют подробные сведения о работоспособности и статусе всех подключенных служб или даже самого сервера. Google «ведет журнал [PLATFORM_NAME]», если вы используете CMS, или «журналы [PROGRAMMING_LANGUAGE]» и «журналы [OPERATING_SYSTEM]», если вы запускаете собственное приложение, чтобы получить дополнительную информацию о поиске рассматриваемых журналов.

Отладка кода или скриптов приложения

Если все остальное не помогает, возможно, проблема в каком-то настраиваемом коде в вашем приложении. Попытайтесь определить причину возникновения проблемы, отладив приложение вручную и проанализировав журналы приложений и серверов. В идеале сделайте копию всего приложения на локальном компьютере разработки и выполните пошаговый процесс отладки, который позволит вам воссоздать точный сценарий, в котором произошла ошибка 410 Gone . и просмотрите код приложения в тот момент, когда что-то пошло не так.

Независимо от причины – и даже если вам удалось ее исправить на этот раз – появления проблемы, такой как 410 Отсутствие ошибки в вашем собственном приложении – хороший признак того, что вы можете захотеть реализовать инструмент управления ошибками, который поможет вам автоматически обнаруживать ошибки и сообщать о них вам в тот момент, когда они возникают.. Программное обеспечение для мониторинга ошибок Airbrake обеспечивает мониторинг ошибок в реальном времени и автоматическую отчетность об исключениях для всех ваших проектов разработки. Современная веб-панель управления Airbrake гарантирует, что вы будете получать круглосуточную информацию о состоянии вашего приложения и количестве ошибок. Независимо от того, над чем вы работаете, Airbrake легко интегрируется со всеми наиболее популярными языками и фреймворками. Кроме того, Airbrake упрощает настройку параметров исключений, предоставляя вам полный контроль над активной системой фильтрации ошибок, поэтому вы собираете только наиболее важные ошибки.

Ознакомьтесь с программным обеспечением Airbrake для мониторинга ошибок сегодня и Убедитесь сами, почему так много лучших инженерных команд мира используют Airbrake, чтобы революционизировать свои методы обработки исключений!

Dec 28, 2017 9:11:23 PM |
410 Gone Error: What It Is and How to Fix It

An in-depth overview of what a 410 Gone Error response is, including troubleshooting tips to help you resolve this error in your own application.

The 410 Gone Error is an HTTP response status code indicating that the resource requested by the client has been permanently deleted, and that the client should not expect an alternative redirection or forwarding address. The 410 Gone code may appear similar to the 404 Not Found code that we looked at few months ago, but the two codes serve a distinctly different purpose. A 404 code indicates that the requested resource is not currently available, but it could be available in future requests. Conversely, a 410 code is an explicit indication that the requested resource used to exist, but it has since been permanently removed and will not be available in the future. Thus, a 404 response code indicates that the user agent (browser) can repeat requests to the same resource URI, while a 410 tells the user agent not to repeat requests to that same resource.

Like most HTTP response codes — especially those that indicate an error — the appearance of a 410 Gone Error can be a challenge to properly diagnose and resolve. With a potential pool of over 50 status codes that represent the complex relationship between the client, a web application, a web server, and often multiple third-party web services, determining the cause of a particular status code can be a challenge under the best of circumstances.

In this article we’ll examine the 410 Gone Error in more detail by looking at what might cause a message, along with a handful of tips for diagnosing and debugging the appearance of this error within your own application. We’ll even examine a number of the most popular content management systems (CMSs) for potential problem areas that could cause your own website to be generating a 410 Gone Error unexpectedly. Let’s dive in!

Server- or Client-Side?

All HTTP response status codes that are in the 4xx category are considered client error responses. These types of messages contrast with errors in the 5xx category, such as the 504 Gateway Timeout Error we explored a while back, which are considered server error responses. That said, the appearance of a 4xx error doesn’t necessarily mean the issue is on the client side, where the «client» is the web browser or device being used to access the application. Oftentimes, if you’re trying to diagnose an issue with your own application, you can immediately ignore most client-side code and components, such as HTML, cascading style sheets (CSS), client-side JavaScript, and so forth. This doesn’t apply solely to web sites, either. Many smart phone apps that have a modern looking user interface are actually powered by a normal web application behind the scenes; one that is simply hidden from the user.

On the other hand, this doesn’t rule out the client as the actual cause of a 410 Gone Error, either. In many cases, the client may be unintentionally sending a request to the wrong resource, which may lead to an 410 Gone Error. We’ll explore some of these scenarios (and potential solutions) down below, but be aware that, even though the 410 Gone Error is considered a client error response, it doesn’t inherently mean we can rule out either the client nor the server as the culprit in this scenario. In these scenarios, the server is still the network object that is producing the 410 Gone Error, and returning it as the HTTP response code to the client, but it could be that the client is causing the issue in some way.

Start With a Thorough Application Backup

As with anything, it’s better to have played it safe at the start than to screw something up and come to regret it later on down the road. As such, it is critical that you perform a full backup of your application, database, and so forth, before attempting any fixes or changes to the system. Even better, if you have the capability, create a complete copy of the application onto a secondary staging server that isn’t «live,» or isn’t otherwise active and available to the public. This will give you a clean testing ground with which to test all potential fixes to resolve the issue, without threatening the security or sanctity of your live application.

Diagnosing a 410 Gone Error

As discussed in the introduction, a 410 Gone Error indicates that the user agent (the web browser, in most cases) has requested a resource that has been permanently deleted from the server. This could happen in a few different circumstances:

  • The server used to have a valid resource available at the requested location, but it was intentionally removed.
  • The server should have a valid resource at the requested location, but it is unintentionally reporting that the resource has been removed.
  • The client is trying to request the incorrect resource.

Troubleshooting on the Client-Side

Since the 410 Gone Error is a client error response code, it’s best to start by troubleshooting any potential client-side issues that could be causing this error. Here are a handful of tips to try on the browser or device that is giving you problems.

Check the Requested URL

The most common cause of a 410 Gone Error is simply inputting an incorrect URL. As discussed before, many web servers are tightly secured to disallow access to improper URLs that the server isn’t prepared to provide access to. This could be anything from trying to access a file directory via a URL to attempting to gain access to a private page meant for other users. Since 410 codes are not as common as 404 codes, the appearance of a 410 usually means that the requested URL was at one time valid, but that is no longer the case. Either way, it’s a good idea to double-check the exact URL that is returning the 410 Gone Error error to make sure it is intended resource.

Debugging Common Platforms

If you’re running common software packages on the server that is responding with the 410 Gone Error, you may want to start by looking into the stability and functionality of those platforms first. The most common content management systems — like WordPress, Joomla!, and Drupal — are all typically well-tested out of the box, but once you start making modifications to the underlying extensions or PHP code (the language in which nearly all modern content management systems are written in), it’s all too easy to cause an unforeseen issue that results in a 410 Gone Error.

There are a few tips below aimed at helping you troubleshoot some of these popular software platforms.

Rollback Recent Upgrades

If you recently updated the content management system itself just before the 410 Gone Error appeared, you may want to consider rolling back to the previous version you had installed when things were working fine. Similarly, any extensions or modules that you may have recently upgraded can also cause server-side issues, so reverting to previous versions of those may also help. For assistance with this task, simply Google «downgrade [PLATFORM_NAME]» and follow along. In some cases, however, certain CMSs don’t really provide a version downgrade capability, which indicates that they consider the base application, along with each new version released, to be extremely stable and bug-free. This is typically the case for the more popular platforms, so don’t be afraid if you can’t find an easy way to revert the platform to an older version.

Uninstall New Extensions, Modules, or Plugins

Depending on the particular content management system your application is using, the exact name of these components will be different, but they serve the same purpose across every system: improving the capabilities and features of the platform beyond what it’s normally capable of out of the box. But be warned: such extensions can, more or less, take full control of the system and make virtually any changes, whether it be to the PHP code, HTML, CSS, JavaScript, or database. As such, it may be wise to uninstall any new extensions that may have been recently added. Again, Google the extension name for the official documentation and assistance with this process.

Check for Unexpected Database Changes

It’s worth noting that, even if you uninstall an extension through the CMS dashboard, this doesn’t guarantee that changes made by the extension have been fully reverted. This is particularly true for many WordPress extensions, which are given carte blanche within the application, including full access rights to the database. Unless the extension author explicitly codes such things in, there are scenarios where an extension may modify database records that don’t «belong» to the extension itself, but are instead created and managed by other extensions (or even the base CMS itself). In those scenarios, the extension may not know how to revert alterations to database records, so it will ignore such things during uninstallation. Diagnosing such problems can be tricky, but I’ve personally encountered such scenarios multiple times, so your best course of action, assuming you’re reasonably convinced an extension is the likely culprit for the 410 Gone Error, is to open the database and manually look through tables and records that were likely modified by the extension.

Above all, don’t be afraid to Google your issue. Try searching for specific terms related to your issue, such as the name of your application’s CMS, along with the 410 Gone Error. Chances are you’ll find someone who has experienced the same issue.

Troubleshooting on the Server-Side

If you aren’t running a CMS application — or even if you are, but you’re confident the 410 Gone Error isn’t related to that — here are some additional tips to help you troubleshoot what might be causing the issue on the server-side of things.

Confirm Your Server Configuration

Your application is likely running on a server that is using one of the two most popular web server softwares, Apache or nginx. At the time of publication, both of these web servers make up over 84% of the world’s web server software! Thus, one of the first steps you can take to determine what might be causing these 410 Gone Redirect response codes is to check the configuration files for your web server software for unintentional redirect instructions.

To determine which web server your application is using you’ll want to look for a key file. If your web server is Apache then look for an .htaccess file within the root directory of your website file system. For example, if your application is on a shared host you’ll likely have a username associated with the hosting account. In such a case, the application root directory is typically found at the path of /home/<username>/public_html/, so the .htaccess file would be at /home/<username>/public_html/.htaccess.

If you located the .htaccess file then open it in a text editor and look for lines that use RewriteXXX directives, which are part of the mod_rewrite module in Apache. Covering exactly how these rules work is well beyond the scope of this article, however, the basic concept is that a RewriteCond directive defines a text-based pattern that will be matched against entered URLs. If a matching URL is requested by a visitor to the site, the RewriteRule directive that follows one or more RewriteCond directives is used to perform the actual redirection of the request to the appropriate URL.

For example, here is a simple RewriteRule that matches all incoming requests to https://airbrake.io/expired_page and responding with a 410 Gone Redirect error code:

RewriteEngine on
RewriteRule ^(.*)$ https://airbrake.io/expired_page$1 [R=410,L]

Notice the R=410 flag at the end of the RewriteRule, which explicitly states that the response code should be 410, indicating to user agents that the resource has been permanently deleted and no future requests should be made. Thus, if you find any strange RewriteCond or RewriteRule directives in the .htaccess file that don’t seem to belong, try temporarily commenting them out (using the # character prefix) and restarting your web server to see if this resolves the issue.

On the other hand, if your server is running on nginx, you’ll need to look for a completely different configuration file. By default this file is named nginx.conf and is located in one of a few common directories: /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx. Once located, open nginx.conf in a text editor and look for directives that are using the 410 response code flag. For example, here is a simple block directive (i.e. a named set of directives) that configures a virtual server for airbrake.io and ensures that the error page presented to a user agent that makes a 404 Not Found request is sent to the /deleted.html error page and given a 410 Gone error code response:

server {
listen 80;
listen 443 ssl;
server_name airbrake.io;
error_page 404 =410 /deleted.html;
}

Have a look through your nginx.conf file for any abnormal directives or lines that include the 410 flag. Comment out any abnormalities before restarting the server to see if the issue was resolved.

Configuration options for each different type of web server can vary dramatically, so we’ll just list a few popular ones to give you some resources to look through, depending on what type of server your application is running on:

  • Apache
  • Nginx
  • IIS
  • Node.js
  • Apache Tomcat

Look Through the Logs

Nearly every web application will keep some form of server-side logs. Application logs are typically the history of what the application did, such as which pages were requested, which servers it connected to, which database results it provides, and so forth. Server logs are related to the actual hardware that is running the application, and will often provide details about the health and status of all connected services, or even just the server itself. Google «logs [PLATFORM_NAME]» if you’re using a CMS, or «logs [PROGRAMMING_LANGUAGE]» and «logs [OPERATING_SYSTEM]» if you’re running a custom application, to get more information on finding the logs in question.

Debug Your Application Code or Scripts

If all else fails, it may be that a problem in some custom code within your application is causing the issue. Try to diagnose where the issue may be coming from through manually debugging your application, along with parsing through application and server logs. Ideally, make a copy of the entire application to a local development machine and perform a step-by-step debug process, which will allow you to recreate the exact scenario in which the 410 Gone Error occurred and view the application code at the moment something goes wrong.

No matter the cause — and even if you managed to fix it this time — the appearance of an issue like the 410 Gone Error within your own application is a good indication you may want to implement an error management tool, which will help you automatically detect errors and report them to you at the very moment they occur. Airbrake’s error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.

Check out Airbrake’s error monitoring software today and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices!

Имеем приложение на laravel
Пытаемся сделать интеграцию с Тинькофф Оплата, в которой уведомления о платежах приходят на наш урл (в виде json), а мы должны отвечать кодом 200 и текстом ОК (как, собственно и в других платежных системах)

Проблема в том, что тинькоф отправляет к нам запросы и получает в ответ 410 ошибку (судя по access-логам).
В приложении мы складываем в лог дампы таких запросов. Но почему-то лог пустой. Видимо запрос отваливается с кодом 410 еще до того как доходит до приложения, на уровне apache/nginx.

Пробую отправлять запросы через postman — 200OK, пробую тупо через браузер — 200OK.

91.194.ХХХ.ХХХ — — [26/Apr/2019:11:48:55 +0300] «POST /payment/tinkoff/process HTTP/1.1» 410 170 «-» «Apache-HttpClient/4.5.5 (Java/1.8.0_73)»

91.194.ХХХ.ХХХ — — [26/Apr/2019:11:48:55 +0300] «POST /payment/tinkoff/process HTTP/1.1» 410 170 «-» «Apache-HttpClient/4.5.5 (Java/1.8.0_73)»

81.28.ХХХ.ХХХ — — [26/Apr/2019:09:26:52 +0300] «POST /payment/tinkoff/process HTTP/1.0» 200 927 «-» «PostmanRuntime/7.6.1»

Куда копать?

I’m using nginx-1.6.2,2 and I’d like return error 410 for URL that matches /browse.php?u=http, so requests such as this will get 410:

162.218.208.16 - - [21/Nov/2014:12:35:40 -0500] "GET /browse.php?u=http%3A%2F%2Fwww.bing.com%2Fsearch%3Fq%3DBroke%2C%2BUSA%2Bfiletype%3Apdf%26first%3D0%26count%3D20%26format%3Drss&b=156&f=norefer HTTP/1.1" 403 570 "http://ww.thespacesurf.com/browse.php?u=http%3A%2F%2Fwww.bing.com%2Fsearch%3Fq%3DBroke%2C%2BUSA%2Bfiletype%3Apdf%26first%3D0%26count%3D20%26format%3Drss&b=156&f=norefer" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)"

I don’t really need regex, so something like this, but it’s not working:

location = /browse.php?u=http {
        return 410;
}

couple of days later, I grep -c for 410 in /var/log/nginx-access.log

$ bzip2 -cd /var/log/nginx-access.log.0.bz2 | grep -c ' 410 '
5665
$ 

and that made me feel warm and fuzzy) thanks again!

Понравилась статья? Поделить с друзьями:
  • Nginx ошибка 401
  • Nginx ошибка 408
  • Nginx ошибка 406
  • Nikon d700 ошибка
  • Nginx ошибка 200