Как обойти 401 ошибку

Появление сообщения об ошибке 401 Unauthorized Error («отказ в доступе») при открытии страницы сайта означает неверную авторизацию или аутентификацию пользователя на стороне сервера при обращении к определенному url-адресу. Чаще всего она возникает при ошибочном вводе имени и/или пароля посетителем ресурса при входе в свой аккаунт. Другой причиной являются неправильные настройки, допущенные при администрировании web-ресурса. Данная ошибка отображается в браузере в виде отдельной страницы с соответствующим описанием. Некоторые разработчики интернет-ресурсов, в особенности крупных порталов, вводят собственную дополнительную кодировку данного сбоя:

  • 401 Unauthorized;
  • Authorization Required;
  • HTTP Error 401 – Ошибка авторизации.

Попробуем разобраться с наиболее распространенными причинами возникновения данной ошибки кода HTTP-соединения и обсудим способы их решения.

Причины появления ошибки сервера 401 и способы ее устранения на стороне пользователя

При доступе к некоторым сайтам (или отдельным страницам этих сайтов), посетитель должен пройти определенные этапы получения прав:

  1. Идентификация – получение вашей учетной записи («identity») по username/login или email.
  2. Аутентификация («authentic») – проверка того, что вы знаете пароль от этой учетной записи.
  3. Авторизация – проверка вашей роли (статуса) в системе и решение о предоставлении доступа к запрошенной странице или ресурсу на определенных условиях.

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

Наиболее распространенной причиной появления ошибки с кодом 401 для рядового пользователя является ввод неверных данных при посещении определенного ресурса. В этом и других случаях нужно попробовать сделать следующее:

  1. Проверьте в адресной строке правильность написания URL. Особенно это касается перехода на подстраницы сайта, требующие авторизации. Введите правильный адрес. Если переход на страницу осуществлялся после входа в аккаунт, разлогинитесь, вернитесь на главную страницу и произведите повторный вход с правильными учетными данными.
  2. При осуществлении входа с сохраненными данными пользователя и появлении ошибки сервера 401 проверьте их корректность в соответствующих настройках данного браузера. Возможно, авторизационные данные были вами изменены в другом браузере. Также можно очистить кэш, удалить cookies и повторить попытку входа. При удалении истории браузера или очистке кэша потребуется ручное введение логина и пароля для получения доступа. Если вы не помните пароль, пройдите процедуру восстановления, следуя инструкциям.
  3. Если вы считаете, что вводите правильные регистрационные данные, но не можете получить доступ к сайту, обратитесь к администратору ресурса. В этом случае лучше всего сделать скриншот проблемной страницы.
  4. Иногда блокировка происходит на стороне провайдера, что тоже приводит к отказу в доступе и появлению сообщения с кодировкой 401. Для проверки можно попробовать авторизоваться на том же ресурсе с альтернативного ip-адреса (например, используя VPN). При подтверждении блокировки трафика свяжитесь с провайдером и следуйте его инструкциям.

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

Иногда простая перезагрузка проблемной страницы, выход из текущей сессии или использование другого веб-браузера полностью решают проблему с 401 ошибкой авторизации.

Ошибка 401 - отказ в доступе

Устранение ошибки 401 администратором веб-ресурса 

Для владельцев сайтов, столкнувшихся с появлением ошибки отказа доступа 401, решить ее порою намного сложнее, чем обычному посетителю ресурса. Есть несколько рекомендаций, которые помогут в этом:

  • Обращение в службу поддержки хостинга сайта. Как и в случае возникновения проблем с провайдером, лучше всего подробно описать последовательность действий, приведших к появлению ошибки 401, приложить скриншот.
  • При отсутствии проблем на стороне хостинг-провайдера можно внести следующие изменения в настройки сайта с помощью строки Disallow:/адрес проблемной страницы. Запретить индексацию страницам с ошибкой в «rоbоts.txt», после чего добавить в файл «.htассеss» строку такого типа:
Redirect 301 /oldpage.html http://site.com/newpage.html.

Где в поле /oldpage.html прописывается адрес проблемной страницы, а в http://site.com/newpage.html адрес страницы авторизации.

Таким образом вы перенаправите пользователей со всех страниц, которые выдают ошибку 401, на страницу начальной авторизации.

  • Если после выполнения предыдущих рекомендаций пользователи при попытках авторизации все равно видят ошибку 401, то найдите на сервере файл «php.ini» и увеличьте время жизни сессии, изменив значения следующих параметров: «session.gc_maxlifetime» и «session.cookie_lifetime» на 1440 и 0 соответственно.
  • Разработчики веб-ресурсов могут использовать более сложные методы авторизации и аутентификации доступа для создания дополнительной защиты по протоколу HTTP. Если устранить сбой простыми методами администрирования не удается, следует обратиться к специалистам, создававшим сайт, для внесения соответствующих изменений в код.

Хотя ошибка 401 и является проблемой на стороне клиента, ошибка пользователя на стороне сервера может привести к ложному требованию входа в систему. К примеру, сетевой администратор разрешит аутентификацию входа в систему всем пользователям, даже если это не требуется. В таком случае сообщение о несанкционированном доступе будет отображаться для всех, кто посещает сайт. Баг устраняется внесением соответствующих изменений в настройки.

Дополнительная информация об ошибке с кодом 401

Веб-серверы под управлением Microsoft IIS могут предоставить дополнительные данные об ошибке 401 Unauthorized в виде второго ряда цифр:

  • 401, 1 – войти не удалось;
  • 401, 2 – ошибка входа в систему из-за конфигурации сервера;
  • 401, 3 – несанкционированный доступ из-за ACL на ресурс;
  • 401, 501 – доступ запрещен: слишком много запросов с одного и того же клиентского IP; ограничение динамического IP-адреса – достигнут предел одновременных запросов и т.д.

Более подробную информацию об ошибке сервера 401 при использовании обычной проверки подлинности для подключения к веб-узлу, который размещен в службе MS IIS, смотрите здесь. 

Следующие сообщения также являются ошибками на стороне клиента и относятся к 401 ошибке:

  • 400 Bad Request; 
  • 403 Forbidden; 
  • 404 Not Found;
  • 408 Request Timeout.

Как видим, появление ошибки авторизации 401 Unauthorized не является критичным для рядового посетителя сайта и чаще всего устраняется самыми простыми способами. В более сложной ситуации оказываются администраторы и владельцы интернет-ресурсов, но и они в 100% случаев разберутся с данным багом путем изменения настроек или корректировки html-кода с привлечением разработчика сайта. 

Trying to access a site and being met with an error page is at best inconvenient, whether that site is yours or someone else’s. As with many HTTP response codes, part of what makes a 401 error so frustrating is the lack of information it offers for diagnosing and resolving the issue.

The 401 error can happen with any browser, so it’s a pretty common issue people face. In most cases, this problem is relatively simple and straightforward to fix.

In this post, we’ll explain what 401 error messages are and why they happen. Then, we’ll walk you through five methods you can use to fix them.

Let’s get started!

What is the 401 Error Code?

The Internet Engineering Task Force (IETF) defines the error 401 Unauthorized as:

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field containing at least one challenge applicable to the target resource.

An Introduction to the 401 Error Code

HTTP 400 status codes are encountered when there is a problem making a request. A 401 error, in particular, happens when your browser denies you access to the page you’re trying to visit.

As a result, instead of loading the web page, the browser will load an error message. 401 errors can happen within any browser so the message appearing may differ.

For example, in Chrome or Edge, you’ll likely see a paper icon along with a simple message telling you that the page in question isn’t working. It will include the phrase “HTTP Error 401” at the bottom, and instruct you to contact the site’s owner if the problem persists:

http error 401 in Chrome

The 401 Error in Chrome

At other times and in other browsers, you might get a slightly less friendly warning that’s just a blank page with a “401 Authorization Required” message:

401 error Authorization Required

Nginx 401 Authorization Required error message

Other variations include:

  • “HTTP 401 Error – Unauthorized”
  • “401 Unauthorized”
  • “Access Denied”

These errors occur on websites that require a login in order to access them. In most cases, it means that something is either wrong with the credentials or with the browser’s ability to read them as valid.

This is similar to HTTP 403 Forbidden Error, in that access isn’t permitted to the user. However, unlike with the 403 error, the 401 error message indicates that the authentication process failed.

The code is sent via the WWW-Authenticate header, which is responsible for identifying the authentication method used for granting access to a web page or resource.

Error Code HTTP 401 Unauthorized Error
Error Type Commonly a client-side error
Error Variations 401 Authorization Required
401 Unauthorized
HTTP 401 Error – Unauthorized
Access Denied
Error Causes Outdated Browser Cache and Cookies
Plugin Incompatibility
Incorrect URL or Outdated Link

The HTTP 401 error is all too common 🤦‍♀️ — and this guide will give you everything you need to fix it the next time you see that message showing up ✅Click to Tweet

What Causes a 401 Error?

If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.

401 errors occur on restricted resources, such as password-protected pages of your WordPress site. So it’s safe to assume that the cause of the problem has something to do with the authentication credentials.

Outdated Browser Cache and Cookies

One of the most common reasons you might experience a 401 error is that your browser’s cache and cookies are out of date, preventing the authorization from successfully going through. If your browser isn’t using the valid authentication credentials (or any at all), the server will reject the request.

Plugin Incompatibility

At other times, this error is caused by a plugin incompatibility or error. For example, a firewall or security plugin can mistake your login attempt as malicious activity, and return a 401 error to protect the page.

Incorrect URL or Outdated Link

It’s also possible that the source of the problem can be attributed to a minor mistake. Common culprits in this category include an incorrectly-typed URL or an outdated link.

How to Fix the 401 Error?

Now that we’ve gone through a bit of background on the 401 error, it’s time to discuss how you can resolve it.

Let’s take a look at five methods you can use:

1. Look for Errors in the URL

We’ll start off with the easiest potential fix: making sure you used the correct URL. This may sound simple, but 401 errors can sometimes appear if the URL wasn’t correctly entered in.

Another possibility is that the link you used to visit the page in question points to the wrong URL. For example, it might be outdated, or leading to a page that no longer exists (and no redirects are in place).

Therefore, it’s worth double-checking the URL you used. If you typed it in yourself, verify that you spelled everything correctly. If you clicked on a link, confirm that it’s pointing to the page you’re trying to access (or try to visit that page directly through the website).

2. Clear Your Browser’s Cache

Your browser’s cache is designed to improve your online experience, by reducing page loading times. Unfortunately, sometimes it can also cause unwanted interruptions.

As we mentioned earlier, one of the common causes of the 401 error is outdated or incorrect cache data or cookies. Therefore, if you don’t notice any issues with the page’s URL, the next step is to clear your browser’s cache.

This will clean out any invalid information that’s locally stored in your browser, which could be interrupting the authentication process. Similarly, your browser’s cookies might contain authentication data that simply needs to be refreshed.

If you’re a Google Chrome user, you can do this by clicking on the menu icon in the top-right corner of the browser, and then going to Settings. Under the Privacy and security section, click on Clear browsing data:

clear browsing data to fix 401 error

The Clear browsing data section in Google Chrome

A new window will open. Under the Basic tab, make sure all three boxes are selected, and then select Clear data:

chrome clear data

The clear browsing data window in Chrome

This process will look a little different in other browsers. For example, in Mozilla Firefox, you would click on the library icon in the top-right corner of the browser, followed by History > Clear Recent History:

firefox clear history

The ‘clear recent history’ option in Firefox settings

In the panel that opens next, select Everything in the drop-down menu at the top, make sure “Cache” is selected, and then click on the Clear Now button:

clear firefox cache

The ‘Clear History’ panel in Firefox

If you’re using a different browser, please refer to this guide for clearing the cache

3. Flush Your DNS

Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.

To do this in Windows, click on the Start button and type cmd into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns, and then hit Enter again:

command prompt

The Command Prompt interface in Windows

On a Mac, you can do this by going to Finder > Applications > Utilities > Terminal:

The Terminal application on Mac

The Terminal application on Mac

Input the command line sudo killall -HUP mDNSResponder and press Enter. Then, you can try refreshing the page you were trying to visit, to see if the 401 error has been resolved.

4. Deactivate Your WordPress Plugins

The problem causing your 401 error might not be due to your browser. If you’re having trouble accessing your WordPress site, it’s also possible that one or more plugins are to blame.

Some plugins, especially security-focused plugins, are configured to show a 401 error when they suspect suspicious login activity that might indicate an attack. Others might just be suffering from compatibility issues. Therefore, it’s a good idea to deactivate all of your WordPress plugins and see if that resolves the issue.

You can deactivate your plugins all at the same time in your dashboard, by going to Plugins > Installed Plugins. Check the box at the top to select all of them. Then under the Bulk Actions drop-down menu, select Deactivate and click on the Apply button:

The plugin deactivation setting in the WordPress dashboard

The plugin deactivation setting in the WordPress dashboard

After that, try reloading the page that returned the 401 error to see if this has resolved the issue. If it has, you can manually activate each plugin one at a time, in order to determine which one is causing the problem.

Then you can remove that plugin, replace it with a new one, or contact its developer for assistance.

5. Check the WWW-Authenticate Header Response

At this point, if the issue hasn’t been fixed, it may be caused by a server-side problem. This means our last fix will be a bit more involved.

As we saw earlier, the 401 response is sent through the WWW-Authenticate header, which appears as “WWW-Authenticate: <type> realm=<realm>”. It includes ‘challenges’, or strings of data that indicate what type of authentication is required in order for access to be granted.

In a nutshell, you’ll want to check and see if the header response was sent, and more specifically, what authentication scheme was used. At the very least, this can help narrow down the cause of the problem, and bring you one step closer to a solution.

To do this, go to the web page that’s displaying the 401 error, and access the developer console in Chrome. You can right-click on the page and select Inspect, or use Ctrl+Shift+J.

Next, click on the Network tab and reload the page. This will generate a list of resources. Select the Status header to sort the table and locate the 401 status code:

network status 401 error

The 401 status code in the developer console in Chrome

Select that entry, and then click on the Headers tab. Under Response Headers, locate the WWW-Authenticate header:

www authenticate header

The Response Headers section of the developer console

The information that is present in the response header, particularly the authentication schemes, can give you more information about what’s happening and point you towards a solution. It can help you understand what type of authentication the server is expecting.

For example, in the above example, we can see that the authentication scheme is “Basic”. This means the authentication request should only require an ID and password. For more detailed information and instructions on how to use this information, we recommend referring to the HTTP Authentication Scheme Registry.

HTTP 401 errors, begone! 🧙‍♂️ 5 ways to stop those pesky messages (no magic required) ✨Click to Tweet

Summary

When your browser and server have trouble communicating or authenticating requests, you’re sometimes forced to deal with errors such as the 401 error. While this problem is irritating, the message is usually temporary and fixable.

Here are five methods you can use to fix the 401 error:

  1. Look for errors in the URL.
  2. Clear your browser’s cache.
  3. Flush your DNS.
  4. Deactivate your WordPress plugins.
  5. Check the WWW-Authenticate header response.

Страница с ошибкой при обращении к WordPress-сайту всегда вызывает неудобства, вне зависимости от того, ваш это сайт или чужой. Как и в случае со многими другими кодами ответов HTTP, ошибка 401 не содержит детальных данных для диагностики и решения проблемы.

Ошибка 401 может появиться в любом браузере. В большинстве случаев ее легко решить.

В этой статье мы расскажем, что означает 401 ошибка, почему она происходит, и какие методы ее устранения существуют.

Итак, приступим!

Содержание

  1. Код ошибки 401 – что это?
  2. Что вызывает ошибку 401
  3. Как исправить ошибку 401 (5 методов)

Код ошибки 401 – что это?

Коды состояния HTTP 400 возникают в случае проблем с выполнением запросов. В частности, ошибка 401 появляется, когда браузер отказывает вам в доступе к странице, которую вы хотите посетить.

В результате вместо загрузки страниц браузер выведет сообщение об ошибке. Ошибки 401 могут возникать в любом браузере, потому отображаемое сообщение может варьироваться.

К примеру, в Chrome и Edge вы, скорее всего, увидите иконку бумаги с простым сообщением о том, что запрашиваемая страница не отвечает. Вы увидите фразу «HTTP Error 401». Вам будет предложено связаться с владельцем сайта, если ошибка не пропадет:

В иных случаях и в других браузерах вы можете получить менее дружелюбное предупреждение. К примеру, может выводиться пустая страница с сообщением «401 Authorization Required»:

Другие вариации текста:

  • HTTP 401 Error – Unauthorized
  • 401 Unauthorized
  • Access Denied

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

Эта ошибка похожа на HTTP 403 Forbidden Error, когда доступ к сайту для пользователя запрещен. Однако, в отличие от ошибки 403, сообщение об ошибке 401 указывает, что процесс аутентификации завершился неудачно.

Код ошибки передается через заголовок WWW-Authenticate, который отвечает за определение метода аутентификации, используемого для предоставления доступа к веб-странице или ресурсу.

Что вызывает ошибку 401

Если вы столкнулись с кодом ошибки в кодах 400, вы должны знать, что проблема произошла на стороне клиента (либо на стороне браузера). Случается, что виновником проблемы является браузер, но так бывает не всегда. Об этом мы еще расскажем позже.

Ошибки 401 возникают на ресурсах с ограниченным доступом – к примеру, на страницах, защищенных паролем. Потому можно предположить, что причина проблемы связана с данными аутентификации.

Устаревшие Cookie и кэш браузера

Одной из наиболее распространенных причин возникновения ошибки 401 является то, что кэш и файлы cookie вашего браузера устарели, что не позволяет выполнить авторизацию. Если ваш браузер использует недействительные данные для авторизации (либо вообще их не использует их), сервер отклонит запрос.

Несовместимые плагины

Также бывают ситуации, когда ошибка вызвана несовместимостью плагинов или какими-либо сбоями в них. К примеру, плагин безопасности может ошибочно принять вашу попытку входа за вредоносную активность, а потому будет возвращена ошибка 401 для защиты страницы.

Неверный URL или устаревшая ссылка

Бывает, что источником проблемы является незначительная оплошность. К примеру, был неверно введен URL, ссылка была устаревшей и т.д.

Как исправить ошибку 401 (5 методов)

Теперь, когда мы разобрались с причинами ошибки 401, пришло время обсудить, как ее устранить.

Давайте рассмотрим 5 методов, которые вы можете использовать.

  1. Проверьте ваш URL.

Начнем с самого простого потенциального решения: убедитесь, что вы использовали верный URL. Это может выглядеть банально, но 401 ошибки нередко появляются, если URL-адрес был введен неправильно.

Еще один вариант: ссылка, которую вы использовали для перехода на запрашиваемую страницу, указывает на неправильный URL. К примеру, ссылка устарела, ведет на страницу, которой больше нет (и редиректов не задано).

Стоит тщательно перепроверить URL-адрес, который вы использовали. Если вы набирали адрес самостоятельно, убедитесь, что все написано безошибочно. Если вы переходили по ссылке, убедитесь в том, что она ведет на страницу, к которой вы хотите получить доступ (либо попробуйте перейти на эту страницу непосредственно через сайт).

  1. Почистите кэш браузера.

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

Как мы уже говорили выше, одной из распространенных причин появления ошибки 401 являются устаревшие или неправильные данные кэша или cookies. Потому, если URL введен верно, следующий шаг – чистка кэша браузера.

В итоге вы удалите любую недействительную информацию, которая хранится локально в вашем браузере и может приводить к прерываниям процесса аутентификации.  Аналогично, файлы cookie вашего браузера могут содержать аутентификационные данные, которые нужно обновить.

Если вы пользуетесь Chrome, вам нужно щелкнуть по иконке с меню в правом верхнем углу браузера и выбрать пункт Settings. В разделе «Privacy and security» нажмите «Clear browsing data:»

Далее вводим URL требуемого сайта и очищаем для него данные.

В других браузерах процесс очистки кэша и cookie может отличаться. К примеру, в Firefox нужно щелкать по иконке с библиотекой и выбирать History > Clear Recent History:

Информацию по остальным браузерам вы можете найти в поисковиках.

  1. Очистка DNS.

Еще один метод, который вы можете попробовать для устранения ошибки 401 – это очистка DNS. Эта причина встречается относительно редко, но стоит попробовать и такой подход, особенно если первые два ничего не дали.

Чтобы очистить DNS, перейдите в Windows к меню «Пуск» и там уже введите в строку поиска cmd. Нажмите Enter. Откроется командная строка. Далее вставьте команду ipconfig/flushdns, после чего снова нажмите Enter.

Если вы пользуетесь Mac, вы можете открыть командную строку следующим образом: Finder > Applications > Utilities > Terminal.

Введите команду sudo killall -HUP mDNSResponder и нажмите Enter. Затем вы можете обновить страницу, чтобы посмотреть, пропала ли ошибка 401 или нет.

  1. Деактивируйте ваши плагины

Проблема может возникать и по вине плагинов.

Некоторые плагины, особенно связанные с безопасностью, могут выдавать ошибку 401 при подозрении на вредоносную активность. Также у них могут быть проблемы с совместимостью. Потому лучше всего деактивировать все плагины и посмотреть, будет ли страница работать.

Вы можете деактивировать все плагины разом, перейдя в раздел Plugins > Installed Plugins в консоли WordPress. Выберите все плагины и в меню Bulk Actions задайте Deactivate, после чего щелкните по кнопке Apply:

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

Далее вы уже можете либо удалить плагин, либо написать его разработчикам, чтобы они предоставили рабочее решение.

  1. Проверьте заголовок WWW-Authenticate

Если проблема все еще остается, то в таком случае она может быть связана с ошибками на сервере. А значит, исправить ее будет чуть сложнее.

Как мы уже писали ранее, ответ 401 передается через заголовок WWW-Authenticate, который отображается как “WWW-Authenticate: <type> realm=<realm>”. Он включает в себя строки данных, указывающие на то, какой тип аутентификации требуется для предоставления доступа.

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

Перейдите на страницу с ошибкой 401 и откройте консоль разработчика в Chrome. Вы можете щелкнуть правой кнопкой мыши на странице и выбрать Inspect (Ctrl+Shift+J).

Далее перейдите на вкладку Network и перезагрузите страницу. Это позволит сгенерировать список ресурсов. Выберите заголовок Status, чтобы отсортировать таблицу, и найдите код 401:

Выберите данную запись, после чего перейдите на вкладку Headers. В Response Headers найдите заголовок WWW-Authenticate:

Информация, представленная в заголовке ответа, в частности, в схеме аутентификации, даст вам больше сведений о том, что произошло, и укажет на решение. Это позволит вам понять, какой тип аутентификации требуется серверу.

К примеру, в приведенном выше примере мы видим, что схема аутентификации задана как «Basic». Это означает, что запрос аутентификации требует только ID и password. Для получения более подробной информации и инструкций мы рекомендуем обратиться к HTTP Authentication Scheme Registry.

Источник: kinsta.com

Страница с ошибкой при обращении к WordPress-сайту всегда вызывает неудобства, вне зависимости от того, ваш это сайт или чужой. Как и в случае со многими другими кодами ответов HTTP, ошибка 401 не содержит детальных данных для диагностики и решения проблемы.

Ошибка 401 может появиться в любом браузере. В большинстве случаев ее легко решить.

В этой статье мы расскажем, что означает 401 ошибка, почему она происходит, и какие методы ее устранения существуют.

Итак, приступим!

Содержание

  1. Код ошибки 401 – что это?
  2. Что вызывает ошибку 401
  3. Как исправить ошибку 401 (5 методов)

Код ошибки 401 – что это?

Коды состояния HTTP 400 возникают в случае проблем с выполнением запросов. В частности, ошибка 401 появляется, когда браузер отказывает вам в доступе к странице, которую вы хотите посетить.

В результате вместо загрузки страниц браузер выведет сообщение об ошибке. Ошибки 401 могут возникать в любом браузере, потому отображаемое сообщение может варьироваться.

К примеру, в Chrome и Edge вы, скорее всего, увидите иконку бумаги с простым сообщением о том, что запрашиваемая страница не отвечает. Вы увидите фразу «HTTP Error 401». Вам будет предложено связаться с владельцем сайта, если ошибка не пропадет:

В иных случаях и в других браузерах вы можете получить менее дружелюбное предупреждение. К примеру, может выводиться пустая страница с сообщением «401 Authorization Required»:

Другие вариации текста:

  • HTTP 401 Error – Unauthorized
  • 401 Unauthorized
  • Access Denied

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

Эта ошибка похожа на HTTP 403 Forbidden Error, когда доступ к сайту для пользователя запрещен. Однако, в отличие от ошибки 403, сообщение об ошибке 401 указывает, что процесс аутентификации завершился неудачно.

Код ошибки передается через заголовок WWW-Authenticate, который отвечает за определение метода аутентификации, используемого для предоставления доступа к веб-странице или ресурсу.

Что вызывает ошибку 401

Если вы столкнулись с кодом ошибки в кодах 400, вы должны знать, что проблема произошла на стороне клиента (либо на стороне браузера). Случается, что виновником проблемы является браузер, но так бывает не всегда. Об этом мы еще расскажем позже.

Ошибки 401 возникают на ресурсах с ограниченным доступом – к примеру, на страницах, защищенных паролем. Потому можно предположить, что причина проблемы связана с данными аутентификации.

Устаревшие Cookie и кэш браузера

Одной из наиболее распространенных причин возникновения ошибки 401 является то, что кэш и файлы cookie вашего браузера устарели, что не позволяет выполнить авторизацию. Если ваш браузер использует недействительные данные для авторизации (либо вообще их не использует их), сервер отклонит запрос.

Несовместимые плагины

Также бывают ситуации, когда ошибка вызвана несовместимостью плагинов или какими-либо сбоями в них. К примеру, плагин безопасности может ошибочно принять вашу попытку входа за вредоносную активность, а потому будет возвращена ошибка 401 для защиты страницы.

Неверный URL или устаревшая ссылка

Бывает, что источником проблемы является незначительная оплошность. К примеру, был неверно введен URL, ссылка была устаревшей и т.д.

Как исправить ошибку 401 (5 методов)

Теперь, когда мы разобрались с причинами ошибки 401, пришло время обсудить, как ее устранить.

Давайте рассмотрим 5 методов, которые вы можете использовать.

  1. Проверьте ваш URL.

Начнем с самого простого потенциального решения: убедитесь, что вы использовали верный URL. Это может выглядеть банально, но 401 ошибки нередко появляются, если URL-адрес был введен неправильно.

Еще один вариант: ссылка, которую вы использовали для перехода на запрашиваемую страницу, указывает на неправильный URL. К примеру, ссылка устарела, ведет на страницу, которой больше нет (и редиректов не задано).

Стоит тщательно перепроверить URL-адрес, который вы использовали. Если вы набирали адрес самостоятельно, убедитесь, что все написано безошибочно. Если вы переходили по ссылке, убедитесь в том, что она ведет на страницу, к которой вы хотите получить доступ (либо попробуйте перейти на эту страницу непосредственно через сайт).

  1. Почистите кэш браузера.

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

Как мы уже говорили выше, одной из распространенных причин появления ошибки 401 являются устаревшие или неправильные данные кэша или cookies. Потому, если URL введен верно, следующий шаг – чистка кэша браузера.

В итоге вы удалите любую недействительную информацию, которая хранится локально в вашем браузере и может приводить к прерываниям процесса аутентификации.  Аналогично, файлы cookie вашего браузера могут содержать аутентификационные данные, которые нужно обновить.

Если вы пользуетесь Chrome, вам нужно щелкнуть по иконке с меню в правом верхнем углу браузера и выбрать пункт Settings. В разделе «Privacy and security» нажмите «Clear browsing data:»

Далее вводим URL требуемого сайта и очищаем для него данные.

В других браузерах процесс очистки кэша и cookie может отличаться. К примеру, в Firefox нужно щелкать по иконке с библиотекой и выбирать History > Clear Recent History:

Информацию по остальным браузерам вы можете найти в поисковиках.

  1. Очистка DNS.

Еще один метод, который вы можете попробовать для устранения ошибки 401 – это очистка DNS. Эта причина встречается относительно редко, но стоит попробовать и такой подход, особенно если первые два ничего не дали.

Чтобы очистить DNS, перейдите в Windows к меню «Пуск» и там уже введите в строку поиска cmd. Нажмите Enter. Откроется командная строка. Далее вставьте команду ipconfig/flushdns, после чего снова нажмите Enter.

Если вы пользуетесь Mac, вы можете открыть командную строку следующим образом: Finder > Applications > Utilities > Terminal.

Введите команду sudo killall -HUP mDNSResponder и нажмите Enter. Затем вы можете обновить страницу, чтобы посмотреть, пропала ли ошибка 401 или нет.

  1. Деактивируйте ваши плагины

Проблема может возникать и по вине плагинов.

Некоторые плагины, особенно связанные с безопасностью, могут выдавать ошибку 401 при подозрении на вредоносную активность. Также у них могут быть проблемы с совместимостью. Потому лучше всего деактивировать все плагины и посмотреть, будет ли страница работать.

Вы можете деактивировать все плагины разом, перейдя в раздел Plugins > Installed Plugins в консоли WordPress. Выберите все плагины и в меню Bulk Actions задайте Deactivate, после чего щелкните по кнопке Apply:

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

Далее вы уже можете либо удалить плагин, либо написать его разработчикам, чтобы они предоставили рабочее решение.

  1. Проверьте заголовок WWW-Authenticate

Если проблема все еще остается, то в таком случае она может быть связана с ошибками на сервере. А значит, исправить ее будет чуть сложнее.

Как мы уже писали ранее, ответ 401 передается через заголовок WWW-Authenticate, который отображается как “WWW-Authenticate: <type> realm=<realm>”. Он включает в себя строки данных, указывающие на то, какой тип аутентификации требуется для предоставления доступа.

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

Перейдите на страницу с ошибкой 401 и откройте консоль разработчика в Chrome. Вы можете щелкнуть правой кнопкой мыши на странице и выбрать Inspect (Ctrl+Shift+J).

Далее перейдите на вкладку Network и перезагрузите страницу. Это позволит сгенерировать список ресурсов. Выберите заголовок Status, чтобы отсортировать таблицу, и найдите код 401:

Выберите данную запись, после чего перейдите на вкладку Headers. В Response Headers найдите заголовок WWW-Authenticate:

Информация, представленная в заголовке ответа, в частности, в схеме аутентификации, даст вам больше сведений о том, что произошло, и укажет на решение. Это позволит вам понять, какой тип аутентификации требуется серверу.

К примеру, в приведенном выше примере мы видим, что схема аутентификации задана как «Basic». Это означает, что запрос аутентификации требует только ID и password. Для получения более подробной информации и инструкций мы рекомендуем обратиться к HTTP Authentication Scheme Registry.

Источник: kinsta.com

Trying to access a WordPress site and being met with an error page is at best inconvenient, whether that site is yours or someone else’s. As with many HTTP response codes, part of what makes a 401 error so frustrating is the lack of information it offers for diagnosing and resolving the issue.

The 401 error can happen with any browser, so it’s a pretty common issue people face. In most cases, this problem is relatively simple and straightforward to fix.

In this post, we’ll explain what 401 error messages are and why they happen. Then, we’ll walk you through five methods you can use to fix them.

Let’s get started!

What is the 401 Error Code?

The Internet Engineering Task Force (IETF) defines the error 401 Unauthorized as:

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field containing at least one challenge applicable to the target resource.

An Introduction to the 401 Error Code

HTTP 400 status codes are encountered when there is a problem making a request. A 401 error, in particular, happens when your browser denies you access to the page you’re trying to visit.

As a result, instead of loading the web page, the browser will load an error message. 401 errors can happen within any browser so the message appearing may differ.

For example, in Chrome or Edge, you’ll likely see a paper icon along with a simple message telling you that the page in question isn’t working. It will include the phrase “HTTP Error 401” at the bottom, and instruct you to contact the site’s owner if the problem persists:

http error 401 in Chrome

The 401 Error in Chrome

At other times and in other browsers, you might get a slightly less friendly warning that’s just a blank page with a “401 Authorization Required” message:

401 error Authorization Required

Nginx 401 Authorization Required error message

Other variations include:

  • “HTTP 401 Error – Unauthorized”
  • “401 Unauthorized”
  • “Access Denied”

These errors occur on websites that require a login in order to access them. In most cases, it means that something is either wrong with the credentials or with the browser’s ability to read them as valid.

This is similar to HTTP 403 Forbidden Error, in that access isn’t permitted to the user. However, unlike with the 403 error, the 401 error message indicates that the authentication process failed.

The code is sent via the WWW-Authenticate header, which is responsible for identifying the authentication method used for granting access to a web page or resource.

The HTTP 401 error is all too common 🤦‍♀️ — and this guide will give you everything you need to fix it the next time you see that message showing up ✅Click to Tweet

What Causes a 401 Error?

If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.

401 errors occur on restricted resources, such as password-protected pages of your WordPress site. So it’s safe to assume that the cause of the problem has something to do with the authentication credentials.

Outdated Browser Cache and Cookies

One of the most common reasons you might experience a 401 error is that your browser’s cache and cookies are out of date, preventing the authorization from successfully going through. If your browser isn’t using the valid authentication credentials (or any at all), the server will reject the request.

Plugin Incompatibility

At other times, this error is caused by a plugin incompatibility or error. For example, a firewall or security plugin can mistake your login attempt as malicious activity, and return a 401 error to protect the page.

Incorrect URL or Outdated Link

It’s also possible that the source of the problem can be attributed to a minor mistake. Common culprits in this category include an incorrectly-typed URL or an outdated link.

How to Fix the 401 Error (5 Methods)

Now that we’ve gone through a bit of background on the 401 error, it’s time to discuss how you can resolve it.

Let’s take a look at five methods you can use:

1. Look for Errors in the URL

We’ll start off with the easiest potential fix: making sure you used the correct URL. This may sound simple, but 401 errors can sometimes appear if the URL wasn’t correctly entered in.

Another possibility is that the link you used to visit the page in question points to the wrong URL. For example, it might be outdated, or leading to a page that no longer exists (and no redirects are in place).

Therefore, it’s worth double-checking the URL you used. If you typed it in yourself, verify that you spelled everything correctly. If you clicked on a link, confirm that it’s pointing to the page you’re trying to access (or try to visit that page directly through the website).

2. Clear Your Browser’s Cache

Your browser’s cache is designed to improve your online experience, by reducing page loading times. Unfortunately, sometimes it can also cause unwanted interruptions.

As we mentioned earlier, one of the common causes of the 401 error is outdated or incorrect cache data or cookies. Therefore, if you don’t notice any issues with the page’s URL, the next step is to clear your browser’s cache.

This will clean out any invalid information that’s locally stored in your browser, which could be interrupting the authentication process. Similarly, your browser’s cookies might contain authentication data that simply needs to be refreshed.

If you’re a Google Chrome user, you can do this by clicking on the menu icon in the top-right corner of the browser, and then going to Settings. Under the Privacy and security section, click on Clear browsing data:

clear browsing data to fix 401 error

The Clear browsing data section in Google Chrome

A new window will open. Under the Basic tab, make sure all three boxes are selected, and then select Clear data:

chrome clear data

The clear browsing data window in Chrome

This process will look a little different in other browsers. For example, in Mozilla Firefox, you would click on the library icon in the top-right corner of the browser, followed by History > Clear Recent History:

firefox clear history

The ‘clear recent history’ option in Firefox settings

In the panel that opens next, select Everything in the drop-down menu at the top, make sure “Cache” is selected, and then click on the Clear Now button:

clear firefox cache

The ‘Clear History’ panel in Firefox

If you’re using a different browser, please refer to this guide for clearing the cache

3. Flush Your DNS

Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.

To do this in Windows, click on the Start button and type cmd into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns, and then hit Enter again:

command prompt

The Command Prompt interface in Windows

On a Mac, you can do this by going to Finder > Applications > Utilities > Terminal:

The Terminal application on Mac

The Terminal application on Mac

Input the command line sudo killall -HUP mDNSResponder and press Enter. Then, you can try refreshing the page you were trying to visit, to see if the 401 error has been resolved.

4. Deactivate Your WordPress Plugins

The problem causing your 401 error might not be due to your browser. If you’re having trouble accessing your WordPress site, it’s also possible that one or more plugins are to blame.

Some plugins, especially security-focused plugins, are configured to show a 401 error when they suspect suspicious login activity that might indicate an attack. Others might just be suffering from compatibility issues. Therefore, it’s a good idea to deactivate all of your WordPress plugins and see if that resolves the issue.

You can deactivate your plugins all at the same time in your dashboard, by going to Plugins > Installed Plugins. Check the box at the top to select all of them. Then under the Bulk Actions drop-down menu, select Deactivate and click on the Apply button:

The plugin deactivation setting in the WordPress dashboard

The plugin deactivation setting in the WordPress dashboard

After that, try reloading the page that returned the 401 error to see if this has resolved the issue. If it has, you can manually activate each plugin one at a time, in order to determine which one is causing the problem.

Then you can remove that plugin, replace it with a new one, or contact its developer for assistance.

5. Check the WWW-Authenticate Header Response

At this point, if the issue hasn’t been fixed, it may be caused by a server-side problem. This means our last fix will be a bit more involved.

As we saw earlier, the 401 response is sent through the WWW-Authenticate header, which appears as “WWW-Authenticate: <type> realm=<realm>”. It includes ‘challenges’, or strings of data that indicate what type of authentication is required in order for access to be granted.

In a nutshell, you’ll want to check and see if the header response was sent, and more specifically, what authentication scheme was used. At the very least, this can help narrow down the cause of the problem, and bring you one step closer to a solution.

To do this, go to the web page that’s displaying the 401 error, and access the developer console in Chrome. You can right-click on the page and select Inspect, or use Ctrl+Shift+J.

Next, click on the Network tab and reload the page. This will generate a list of resources. Select the Status header to sort the table and locate the 401 status code:

network status 401 error

The 401 status code in the developer console in Chrome

Select that entry, and then click on the Headers tab. Under Response Headers, locate the WWW-Authenticate header:

www authenticate header

The Response Headers section of the developer console

The information that is present in the response header, particularly the authentication schemes, can give you more information about what’s happening and point you towards a solution. It can help you understand what type of authentication the server is expecting.

For example, in the above example, we can see that the authentication scheme is “Basic”. This means the authentication request should only require an ID and password. For more detailed information and instructions on how to use this information, we recommend referring to the HTTP Authentication Scheme Registry.

HTTP 401 errors, begone! 🧙‍♂️ 5 ways to stop those pesky messages (no magic required) ✨Click to Tweet

Summary

When your browser and server have trouble communicating or authenticating requests, you’re sometimes forced to deal with errors such as the 401 error. While this problem is irritating, the message is usually temporary and fixable.

Here are five methods you can use to fix the 401 error:

  1. Look for errors in the URL.
  2. Clear your browser’s cache.
  3. Flush your DNS.
  4. Deactivate your WordPress plugins.
  5. Check the WWW-Authenticate header response.

Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Trying to access a WordPress site and being met with an error page is at best inconvenient, whether that site is yours or someone else’s. As with many HTTP response codes, part of what makes a 401 error so frustrating is the lack of information it offers for diagnosing and resolving the issue.

The 401 error can happen with any browser, so it’s a pretty common issue people face. In most cases, this problem is relatively simple and straightforward to fix.

In this post, we’ll explain what 401 error messages are and why they happen. Then, we’ll walk you through five methods you can use to fix them.

Let’s get started!

What is the 401 Error Code?

The Internet Engineering Task Force (IETF) defines the error 401 Unauthorized as:

The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource. The server generating a 401 response MUST send a WWW-Authenticate header field containing at least one challenge applicable to the target resource.

An Introduction to the 401 Error Code

HTTP 400 status codes are encountered when there is a problem making a request. A 401 error, in particular, happens when your browser denies you access to the page you’re trying to visit.

As a result, instead of loading the web page, the browser will load an error message. 401 errors can happen within any browser so the message appearing may differ.

For example, in Chrome or Edge, you’ll likely see a paper icon along with a simple message telling you that the page in question isn’t working. It will include the phrase “HTTP Error 401” at the bottom, and instruct you to contact the site’s owner if the problem persists:

http error 401 in Chrome

The 401 Error in Chrome

At other times and in other browsers, you might get a slightly less friendly warning that’s just a blank page with a “401 Authorization Required” message:

401 error Authorization Required

Nginx 401 Authorization Required error message

Other variations include:

  • “HTTP 401 Error – Unauthorized”
  • “401 Unauthorized”
  • “Access Denied”

These errors occur on websites that require a login in order to access them. In most cases, it means that something is either wrong with the credentials or with the browser’s ability to read them as valid.

This is similar to HTTP 403 Forbidden Error, in that access isn’t permitted to the user. However, unlike with the 403 error, the 401 error message indicates that the authentication process failed.

The code is sent via the WWW-Authenticate header, which is responsible for identifying the authentication method used for granting access to a web page or resource.

The HTTP 401 error is all too common 🤦‍♀️ — and this guide will give you everything you need to fix it the next time you see that message showing up ✅Click to Tweet

What Causes a 401 Error?

If you encounter an error code in the 400s, you know you’re dealing with a client-side (or browser-side) issue. While the problem may be happening within your browser, however, it doesn’t necessarily always mean that’s the culprit, which we’ll explain in more detail later.

401 errors occur on restricted resources, such as password-protected pages of your WordPress site. So it’s safe to assume that the cause of the problem has something to do with the authentication credentials.

Outdated Browser Cache and Cookies

One of the most common reasons you might experience a 401 error is that your browser’s cache and cookies are out of date, preventing the authorization from successfully going through. If your browser isn’t using the valid authentication credentials (or any at all), the server will reject the request.

Plugin Incompatibility

At other times, this error is caused by a plugin incompatibility or error. For example, a firewall or security plugin can mistake your login attempt as malicious activity, and return a 401 error to protect the page.

Incorrect URL or Outdated Link

It’s also possible that the source of the problem can be attributed to a minor mistake. Common culprits in this category include an incorrectly-typed URL or an outdated link.

How to Fix the 401 Error (5 Methods)

Now that we’ve gone through a bit of background on the 401 error, it’s time to discuss how you can resolve it.

Let’s take a look at five methods you can use:

1. Look for Errors in the URL

We’ll start off with the easiest potential fix: making sure you used the correct URL. This may sound simple, but 401 errors can sometimes appear if the URL wasn’t correctly entered in.

Another possibility is that the link you used to visit the page in question points to the wrong URL. For example, it might be outdated, or leading to a page that no longer exists (and no redirects are in place).

Therefore, it’s worth double-checking the URL you used. If you typed it in yourself, verify that you spelled everything correctly. If you clicked on a link, confirm that it’s pointing to the page you’re trying to access (or try to visit that page directly through the website).

2. Clear Your Browser’s Cache

Your browser’s cache is designed to improve your online experience, by reducing page loading times. Unfortunately, sometimes it can also cause unwanted interruptions.

As we mentioned earlier, one of the common causes of the 401 error is outdated or incorrect cache data or cookies. Therefore, if you don’t notice any issues with the page’s URL, the next step is to clear your browser’s cache.

This will clean out any invalid information that’s locally stored in your browser, which could be interrupting the authentication process. Similarly, your browser’s cookies might contain authentication data that simply needs to be refreshed.

If you’re a Google Chrome user, you can do this by clicking on the menu icon in the top-right corner of the browser, and then going to Settings. Under the Privacy and security section, click on Clear browsing data:

clear browsing data to fix 401 error

The Clear browsing data section in Google Chrome

A new window will open. Under the Basic tab, make sure all three boxes are selected, and then select Clear data:

chrome clear data

The clear browsing data window in Chrome

This process will look a little different in other browsers. For example, in Mozilla Firefox, you would click on the library icon in the top-right corner of the browser, followed by History > Clear Recent History:

firefox clear history

The ‘clear recent history’ option in Firefox settings

In the panel that opens next, select Everything in the drop-down menu at the top, make sure “Cache” is selected, and then click on the Clear Now button:

clear firefox cache

The ‘Clear History’ panel in Firefox

If you’re using a different browser, please refer to this guide for clearing the cache

3. Flush Your DNS

Another method you can try to resolve the 401 error is flushing your Domain Name Server (DNS). While this is a rarer issue, it can be a possible cause, so it’s worth giving it a try if the first two solutions don’t work.

To do this in Windows, click on the Start button and type cmd into the search bar. Hit Enter, and the Command Prompt will open. Copy and paste the command ipconfig/flushdns, and then hit Enter again:

command prompt

The Command Prompt interface in Windows

On a Mac, you can do this by going to Finder > Applications > Utilities > Terminal:

The Terminal application on Mac

The Terminal application on Mac

Input the command line sudo killall -HUP mDNSResponder and press Enter. Then, you can try refreshing the page you were trying to visit, to see if the 401 error has been resolved.

4. Deactivate Your WordPress Plugins

The problem causing your 401 error might not be due to your browser. If you’re having trouble accessing your WordPress site, it’s also possible that one or more plugins are to blame.

Some plugins, especially security-focused plugins, are configured to show a 401 error when they suspect suspicious login activity that might indicate an attack. Others might just be suffering from compatibility issues. Therefore, it’s a good idea to deactivate all of your WordPress plugins and see if that resolves the issue.

You can deactivate your plugins all at the same time in your dashboard, by going to Plugins > Installed Plugins. Check the box at the top to select all of them. Then under the Bulk Actions drop-down menu, select Deactivate and click on the Apply button:

The plugin deactivation setting in the WordPress dashboard

The plugin deactivation setting in the WordPress dashboard

After that, try reloading the page that returned the 401 error to see if this has resolved the issue. If it has, you can manually activate each plugin one at a time, in order to determine which one is causing the problem.

Then you can remove that plugin, replace it with a new one, or contact its developer for assistance.

5. Check the WWW-Authenticate Header Response

At this point, if the issue hasn’t been fixed, it may be caused by a server-side problem. This means our last fix will be a bit more involved.

As we saw earlier, the 401 response is sent through the WWW-Authenticate header, which appears as “WWW-Authenticate: <type> realm=<realm>”. It includes ‘challenges’, or strings of data that indicate what type of authentication is required in order for access to be granted.

In a nutshell, you’ll want to check and see if the header response was sent, and more specifically, what authentication scheme was used. At the very least, this can help narrow down the cause of the problem, and bring you one step closer to a solution.

To do this, go to the web page that’s displaying the 401 error, and access the developer console in Chrome. You can right-click on the page and select Inspect, or use Ctrl+Shift+J.

Next, click on the Network tab and reload the page. This will generate a list of resources. Select the Status header to sort the table and locate the 401 status code:

network status 401 error

The 401 status code in the developer console in Chrome

Select that entry, and then click on the Headers tab. Under Response Headers, locate the WWW-Authenticate header:

www authenticate header

The Response Headers section of the developer console

The information that is present in the response header, particularly the authentication schemes, can give you more information about what’s happening and point you towards a solution. It can help you understand what type of authentication the server is expecting.

For example, in the above example, we can see that the authentication scheme is “Basic”. This means the authentication request should only require an ID and password. For more detailed information and instructions on how to use this information, we recommend referring to the HTTP Authentication Scheme Registry.

HTTP 401 errors, begone! 🧙‍♂️ 5 ways to stop those pesky messages (no magic required) ✨Click to Tweet

Summary

When your browser and server have trouble communicating or authenticating requests, you’re sometimes forced to deal with errors such as the 401 error. While this problem is irritating, the message is usually temporary and fixable.

Here are five methods you can use to fix the 401 error:

  1. Look for errors in the URL.
  2. Clear your browser’s cache.
  3. Flush your DNS.
  4. Deactivate your WordPress plugins.
  5. Check the WWW-Authenticate header response.

Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275+ PoPs worldwide

Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

Facing 401 Unauthorized Error?

Here’s the fix. But first, listen to this:

Несомненно, вы столкнулись с ошибкой или двумя при просмотре ваших любимых веб-сайтов в Интернете. Эти ошибки — обычная неприятность, которую не любят видеть и веб-мастера, и потребители.

Тем не менее, эти неудобства выдерживают и продолжают беспокоить людей даже сегодня.

Но что именно эти коды ошибок появляются из ниоткуда и не объясняют, почему они появились в первую очередь?

Проще говоря, Интернет или Всемирная паутина функционируют на основе прикладного протокола, предназначенного для распределенных и совместных гипермедиа информационных систем, иначе называемых HTTP или протокол передачи гипертекста.

Другими словами, HTTP обеспечивает связь между клиентами и серверами, что позволяет беспрепятственно передавать данные между ними.

Однако, когда где-то по пути возникает проблема со связью, возникает ошибка, помеченная как код состояния ответа. Наиболее распространенные ошибки — это ошибки 4xx, которые представляют проблему или проблему. Имея это в виду, давайте сосредоточимся на несанкционированной ошибке 401 и на том, как ее исправить.

Типы ошибок 4xx

Ошибки или коды состояния, начинающиеся с цифры 4, часто относятся к ошибкам клиента. Другими словами, проблемы имеют отношение к клиентским запросам или напрямую связаны с клиентами.

Более того, эти ошибки могут указывать на временную или постоянную ситуацию. Вот несколько примеров 400 кодов ошибок.

  • Ошибка 400: Плохой запрос — в этом случае сервер не будет или не сможет обработать запрос по различным причинам, таким как некорректное формирование сообщения запроса, неверный синтаксический запрос, запрос обмана при маршрутизации и т. Д. Проще говоря, сервер не понимает, что вы хотите от него.
  • Ошибка 401: Несанкционированный. В центре нашей темы сегодня ошибка 401, аналогичная ошибке 403 Forbidden. Это происходит, когда вы пытаетесь войти с неправильными учетными данными слишком много раз, поэтому сервер решает не пускать вас. Вы, вероятно, сделали опечатку так стыдно за вас. Эта блокировка временная и обычно длится около 30 минут. Реальная проблема — когда вы получаете эту ошибку, но вы уверены, что не сделали ошибку.
  • Ошибка 403: Forbidden — все хорошо, но сервер отказывается действовать. Почему, сервер, почему? самая распространенная проблема здесь, вероятно, проблема с настройкой разрешений. Проще говоря, сервер считает, что у вас нет разрешения на доступ к ресурсу независимо от вашей аутентификации.
  • Ошибка 404: Not Found – The all-time famous “Oops, something went wrong” or “Sorry, the page could not be found” error is probably the most common type of client status codes. As you probably guessed, this error occurs when the resource doesn’t exist or it isn’t available at the moment but may be so in the future.

Теперь, когда мы лучше понимаем эти надоедливые коды ошибок, пришло время сосредоточиться на 401 и как избавиться от него.

Как упоминалось ранее, если вы сталкиваетесь с ошибкой 401, это обычно означает, что вы указали неверные учетные данные для входа, которые сервер не смог распознать.

Тем не менее, что происходит, когда вы фактически предоставляете правильные учетные данные для входа, но сервер по-прежнему предоставляет вам неавторизованное сообщение?

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

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

1. Проверьте URL

  • В некоторых случаях вы вводите URL-адрес (Uniform Resource Locator) в браузере вручную, или у вас есть устаревший URL-адрес, добавленный в закладки, поэтому вы используете его. Это распространенная ошибка, которую можно исправить, проверив орфографические ошибки или проверив, является ли URL-адрес все еще жизнеспособным.

URL

2. Проверьте свои учетные данные

  • Вы будете удивлены, что опечатки являются наиболее распространенной причиной нашей проблемы 401. Правописных ошибок в учетных данных можно избежать с помощью таких инструментов, как Dashlane — вам не нужно будет повторно вводить учетные данные при каждом входе в систему.

3. Очистить историю просмотров и куки

  • Сегодня никто не очищает историю посещений или куки больше и практически никогда. Помимо сбора большого количества цифрового мусора с течением времени, эта привычка может также вызвать ошибку 401 при попытке войти на любой веб-сайт, который вы предпочитаете. Дело в том, что файлы cookie представляют собой фрагменты, которые хранят некоторую вашу личную информацию, включая учетные данные для входа. Они могут напоминать веб-сайту о том, кем вы являетесь, но они не всегда работают правильно. Если вы получаете 401, но уверены, что это не опечатка, попробуйте очистить историю просмотров, файлы cookie и кэш, а затем повторите попытку. Вот как вы можете это сделать.
  • Для Mozilla Firefox — Перейдите в меню гамбургера, нажмите «Параметры», перейдите в «Конфиденциальность и настройки» и найдите «История», нажмите «Очистить историю» и выберите «Все», чтобы полностью избавиться от файлов cookie.

401 Unauthorized Error: firefox optionsконфиденциальность firefix401 Unauthorized Error: firefox setting

  • Для Google Chrome – Got to the dot menu in the upper-right corner, click on it, select Settings > Advanced > Clear Browsing Data.

401 Unauthorized Error: chrome settings

401 Unauthorized Error: chrome settings1401 Unauthorized Error: chrome settings1

  • Для сафари — Просто нажмите «Очистить историю» в меню «История», и все готово.

401 Unauthorized Error: safari clear history

4. Флеш DNS

  • Другим виновником ошибок 401 может быть проблема сервера DNS (Domain Name System). К счастью, эту проблему довольно легко решить.
  • Для пользователей ОС Windows — войдите в свой компьютер как администратор. Введите «CMD» в строке поиска, чтобы открыть командную строку. В командной строке введите следующую команду «ipconfig / flushdns» и нажмите ввод.

окно cmd

  • Для пользователей Mac OS — нажмите Command и пробел, чтобы открыть поиск Spotlight. Когда-то наберите «Терминал». В командном интерфейсе введите следующее: «sudo killall -HUP mDNSResponder».
  • Кроме того, вы пытались выключить, а затем снова включить?

giphy

Теперь, когда мы рассмотрели, что такое неавторизованная ошибка 401 и как ее исправить на стороне клиента, давайте посмотрим, что могут сделать веб-мастера, чтобы избавиться от этих ошибок.

Откат к предыдущей версии

  • Часто веб-мастера используют CMS (систему управления контентом), такую ​​как WordPress, чтобы заниматься своим делом. Каждая CMS время от времени требует обновлений, и эти обновления могут вносить новые ошибки, помимо тех, которые они исправили. Другими словами, обновления нередко вызывают ошибки 401. В этом случае просто откатитесь на предыдущую версию до обновления, где все работало нормально.

Удалить изменения

  • Платформы CMS, такие как WordPress, являющаяся самой популярной, имеют различные дополнения, которые могут помочь веб-мастеру. Эти дополнения включают темы, плагины, виджеты и так далее. Как вы можете себе представить, любое стороннее дополнение может вызвать конфликт с системой, в которой ошибка 401. В таком случае просто удалите все надстройки, которые могли вызвать ошибку.

Влияние ошибок на пользователей

Ошибки — это, мягко говоря, неудобство. Они могут раздражать пользователей и оказывать серьезное негативное влияние на их удовлетворенность и общее восприятие, даже если ошибка произошла из-за ошибки пользователей.

Тем не менее, страница ошибки и сообщение могут быть сделаны интересными и даже интересными, чтобы минимизировать и смягчить разочарование пользователей.

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

But where’s the fun in that? Indeed, a dull message describing a solution to the error may be off-putting, to say the least. That’s why developers oftentimes go a step further to ease the users’ pain.

  • Как пример, страница ошибки 404 Android позволяет вам играть глупо, но тем не менее развлекательная игра, Если вы наткнулись на страницу с ошибкой, вы также можете извлечь из нее выгоду.

404

  • Другим примером может служить Страница ошибки Slack, Хотя красочный пейзаж с интерактивными свиньями и цыплятами может еще больше разжечь ваше разочарование, вы не можете не пролить радостную слезу от смеха.
  • Если вы хотите развлечься, то загляните на страницу ошибок Kualo. Эта веб-хостинговая компания позволяет играть в легендарный космические захватчики тип игры и даже получить скидку, если вы достигнете рекорда.

нет места

В любом случае, даже неудобство может стать возможностью изменить ситуацию и превратить разочарование пользователей в не слишком большое разочарование.

Заключение

В конце концов, все сводится к тому, насколько вы креативны и как вы планируете подходить ко всем ошибкам. Ошибки будут существовать независимо от того, как сильно вы пытаетесь их избежать.

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

Несанкционированная ошибка 401 встречается довольно часто и в основном является результатом неспособности пользователя терпеливо вводить свои учетные данные для входа. Тем не менее, эта ошибка может произойти и по другим причинам.

Вот почему важно понимать, как подойти к проблеме, а также понять, как правильно ее решить.

Категория ~
Что делать (ошибки и проблемы)
– Автор:

Игорь (Администратор)

Сегодня рассмотрим такую специфическую ошибку как 401 Unauthorized Error. Почему специфическую? Потому что обычные пользователи интернета практически никогда не встречаются с данной ошибкой. Но обо всем по порядку.

Что значит ошибка 401 Unauthorized?

Ошибка 401 Unauthorized: что означает и как исправить?

Ошибка 401 Unauthorized («Отказ в доступе») — эта ошибка означает, что при попытке открыть веб-страницу сайта пользователем возникли проблемы с его авторизацией или аутентификацией.

Основная суть. Пользователь пытается открыть страницу. Сайт возвращает страницу с HTTP заголовком WWW-Authenticate (кстати, страница также с кодом 401 Unauthorized), в котором перечислены параметры системы аутентификации. Браузер запрашивает логин и пароль у пользователя, которые передаются в заголовке Authorization обратно к сайту (в соответствии с ранее полученными настройками системы безопасности). Если проверка прошла, то пользователю предоставляется дальше доступ к странице. В противном случае появляется ошибка 401 Unauthorized.

Кстати, стоит понимать, что данная ошибка отличается от 403 Forbidden, хотя и также связана с настройками безопасности.

Возможные причины возникновения ошибки 401 Unauthorized:

1. Некорректно введенные логин или пароль (или их отсутствие). Пользователь что-то некорректно ввел.

2. Недостаточно прав для доступа. Например, в каждом сайте вполне нормальным явлением считается то, что у обычного пользователя нет доступа к административной части сайта.

3. Ошибки в настройках или коде сайта. Такое тоже бывает.

Варианты возможных текстовых уведомлений:

1. HTTP Error 401 — Ошибка авторизации.

2. Требуется авторизация.

3. 401 Несанкционированный доступ.

4. 401 Unauthorized.

5. Authorization Required.

Что делать при ошибке 401 Unauthorized, если вы обычный посетитель сайта?

Рассмотрим что вы можете сделать, если вы обычный пользователь и столкнулись с ошибкой 401 Unauthorized:

1. Введите корректные логин и пароль. Ошибка 401 означает ошибку в авторизации или аутентификации, поэтому стоит проверить правильность введенных вами логина и пароля.

2. Проверьте корректность URL адреса страницы веб-сайта. Если вы не ожидали увидеть 401 Unauthorized (скажем, постоянно открывали сайт без проблем), то вполне нормальным действием будет проверить корректность адреса.

3. Попробуйте открыть страницу через время или с другого браузера. Вполне может быть так, что автор сайта что-то делает с этим самым веб-сайтом. Поэтому стоит подождать какое-то время и попробовать еще раз открыть веб-страницу. Так же может быть так, что ошибка 401 возникает из-за браузера (мало ли чего), поэтому стоит попробовать открыть страницу другим браузером (или с другого компьютера).

Кстати, обзор в тему Зачем пользователю несколько браузеров?

4. Напишите автору сайта. Как минимум узнаете причину или возможное время восстановления доступа.

Как исправить ошибку 401 Unauthorized, если вы владелец сайта?

Теперь рассмотрим как исправить ошибку 401 Unauthorized владельцу сайта:

1. Проверьте URL и логин с паролем. Владелец сайта это тоже пользователь сайта, поэтому проверить адрес страницы и корректность ввода логина с паролем будет не лишним действием.

2. Проверьте настройки и код сайта. Если же вам сайт делал кто-то иной, то попросите его проверить.

3. Напишите хостеру. Если вы все проверили и проблем не обнаружили, то нужно писать хостеру.

Понравилась заметка? Тогда время подписываться в социальных сетях и делать репосты!

☕ Понравился обзор? Поделитесь с друзьями!

  • Ошибка 500 Internal Server Error: что означает и как исправить?

    Ошибка 500 Internal Server Error: что означает и как исправить?
    Что делать (ошибки и проблемы)

  • Ошибка 404 Page Not Found: что означает и как исправить?

    Ошибка 404 Page Not Found: что означает и как исправить?
    Что делать (ошибки и проблемы)

  • Ошибка 403 Forbidden: что означает и как исправить?

    Ошибка 403 Forbidden: что означает и как исправить?
    Что делать (ошибки и проблемы)

  • Ошибка 502 Bad Gateway: что означает и как исправить?

    Ошибка 502 Bad Gateway: что означает и как исправить?
    Что делать (ошибки и проблемы)

  • Ошибка 503 Service Unavailable: что означает и как исправить?

    Ошибка 503 Service Unavailable: что означает и как исправить?
    Что делать (ошибки и проблемы)

  • Коды и ошибки 301, 302, 303, 304

    Коды и ошибки 301, 302, 303, 304
    Что делать (ошибки и проблемы)

Добавить комментарий / отзыв

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The 401 Unauthorized Error is an HTTP status code error that represented the request sent by the client to the server that lacks valid authentication credentials. It may be represented as 401 Unauthorized, Authorization required, HTTP error 401- Unauthorized. It represents that the request could not be authenticated. It consists of a www-Authenticate header which contains the hint on how to authorize correctly. 

    401 Unauthorized Error Occur: This error may occur due to the reasons described below: 

    • It may occur client does not provide the proper authentication credentials to the server within the request time.
    • It may occur when the server rejects the request of the client for some reason even though the client provides proper authentication credentials.
    • When the client is banned for some reason by the server.

    Methods to rectify the error: The 401 Unauthorized error can be fixed by using any of the following ways: 

    • Check The URL: Due to manual errors in typing the URL, the 401 unauthorized error may occur. Hence, checking the URL and rectifying the mistakes in it will fix the 401 error status.
    • Flush the DNS: Errors in DNS also creates 401 error status sometimes. Therefore, clearing the DNS will also rectify this error. In Windows, the DNS can be flushed by typing ipconfig/flushdns in the command prompt and clicking on ENTER.
    • Clear Browser Cookie: In some situations, the cookies may not work smoothly leading to improper server authentication. Thus, by clearing the cookies, the error can be rectified.
    • Logging out and Logging in again: This error may also occur during the maintenance time of the websites. Therefore, visiting the website and logging in again by providing the credentials may also rectify this error.
    • Website mistake: A few times all the above things are good or accurate but still you will get the 401 Unauthorized Error, which is a mistake of the website. That time you need to contact the webmaster of that website and inform that the server is down. You can email them at webmaster@webmaster.com replace the webmaster.com with the website, or you can see the contact us option on any website through that you can inform them.

    Some other ways of 401 Authentication error: This error can occur in the below forms also: 

    • 401.1: This error represents that the login has failed due to some reasons.
    • 401.2: This error represents that the login has failed due to server configuration.
    • 401.3: This error represents that the login has failed due to ACL(Access-control list) on the resource.
    • 401.3: This error represents that the authorization has been failed by the filter.
    • 401.501: This error represents that too many requests have been generated by the client i.e. maximum request limit has been reached by the client.
    • 401.502: This error occurs when any specific client(sam IP) requests multiple times on a single server that the dynamic IP Restriction Concurrent request rate limit reached. Then this error will occur 
       
    • 401.503: This error represents that the IP address of the client is in the deny list of IP restrictions on the server-side.
    • 401.504: This error represents that the Hostname of the client is in the deny list of IP restrictions on the server-side.

    Last Updated :
    24 May, 2021

    Like Article

    Save Article

    Понравилась статья? Поделить с друзьями:
  • Как обозначить речевую ошибку
  • Как обозначить пунктуационную ошибку
  • Как обозначаются орфографические ошибки и пунктуационные
  • Как обозначаются грамматические ошибки
  • Как обозначается фактическая ошибка