Ошибка this request is forbidden

Все мы, путешествуя по просторам интернета, натыкаемся на различные ошибки при загрузке сайтов. Одна из них, кстати, достаточно часто встречается – я говорю об ошибке сервера 403 Forbidden Error. Сегодня я рассмотрю причины ее возникновения и способы устранения со стороны владельца сайта и его пользователя.

Что означает ошибка 403 и почему она появляется

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

  • Формат индексного файла неверен.
  • Некорректно выставленные права на папку/файл.
  • Файлы были загружены в неправильную папку.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Исправление ошибки сервера 403 Forbidden

Чтобы исправить ошибку сервера 403 Forbidden, обязательно нужен доступ к панели управления вашего хостинга. Все описанные ниже шаги применимы к любой CMS, но примеры будут показаны на основе WordPress.

Проверка индексного файла

Сначала я проверю, правильно ли назван индексный файл. Все символы в его имени должны быть в нижнем регистре. Если хотя бы один символ набран заглавной буквой, возникнет ошибка 403 Forbidden. Но это больше относится к ОС Linux, которой небезразличен регистр.

Еще не стоит забывать, что индексный файл может быть нескольких форматов, в зависимости от конфигураций сайта: index.html, index.htm, или index.php. Кроме того, он должен храниться в папке public_html вашего сайта. Файл может затеряться в другой директории только в том случае, если вы переносили свой сайт.

Проверка индексного файла на наличие и правильность ввода

Любое изменение в папке или файле фиксируется. Чтобы узнать, не стала ли ошибка итогом деятельности злоумышленников, просто проверьте графу «Дата изменения».

Настройка прав доступа

Ошибка 403 Forbidden появляется еще тогда, когда для папки, в которой расположен искомый файл, неправильно установлены права доступа. На все директории должны быть установлены права на владельца. Но есть другие две категории:

  • группы пользователей, в числе которых есть и владелец;
  • остальные, которые заходят на ваш сайт.

На директории можно устанавливать право на чтение, запись и исполнение.

Так, по умолчанию на все папки должно быть право исполнения для владельца. Изменить их можно через панель управления TimeWeb. Для начала я зайду в раздел «Файловый менеджер», перейду к нужной папке и выделю ее. Далее жму на пункт меню «Файл», «Права доступа».  

Как изменить права доступа к файлу в файловом менеджере TimeWeb

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

Как должны быть выставлены права доступа для всех папок

Отключение плагинов WordPress

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

Для решения подобной проблемы необходимо просто отключить их. Но сначала надо найти папку с плагинами. Открываю папку своего сайта, перехожу в раздел «wp-content» и нахожу в нем директорию «plugins». Переименовываю папку – выделяю ее, жму на меню «Файл» и выбираю соответствующий пункт. Название можно дать вот такое: «plugins-disable». Данное действие отключит все установленные плагины.

Отключение плагинов через файловый менеджер TimeWeb

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

Но что делать, если у вас плагин не один, а какой из них влияет на работу сайта – неизвестно? Тогда можно вернуть все как было и провести подобные действия с папками для определенных плагинов. Таким образом, они будут отключаться по отдельности. И при этом каждый раз надо перезагружать страницу и смотреть, как работает сайт. Как только «виновник торжества» найден, следует переустановить его, удалить или найти альтернативу.

Читайте также

Ошибки сервера HTTP

Как исправить ошибки SMTP-сервера при отправке писем

Как решить проблему, если вы – пользователь

Выше я рассмотрела способы устранения ошибки 403 Forbidden для владельцев сайта. Теперь же разберу методы исправления в случаях с пользователем.

  • Сначала надо убедиться, что проблема заключается именно в вашем устройстве. Внимательно проверьте, правильно ли вы ввели URL сайта. Может, в нем есть лишние символы. Или, наоборот, какие-то символы отсутствуют.
  • Попробуйте загрузить страницу с другого устройства. Если на нем все будет нормально, значит, проблема кроется именно в используемом вами девайсе. Если нет – надо перейти к последнему шагу.
  • Еще хороший вариант – немного подождать и обновить страницу. Делается это либо кликом по иконке возле адресной строки браузера, либо нажатием на комбинацию Ctrl + F5. Можно и без Ctrl, на ваше усмотрение.
  • Если ничего из вышеперечисленного не помогло, надо очистить кэш и cookies. Провести такую процедуру можно через настройки браузера. Для этого необходимо открыть историю просмотров, чтобы через нее перейти к инструменту очистки. Эту же утилиту часто можно найти в настройках, в разделе «Конфиденциальность и безопасность». В новом окне нужно отметить пункты с кэшем и cookies и нажать на кнопку для старта очистки.Очистка кэша и cookies в браузере Google Chrome
  • Ошибка 403 Forbidden возникает и тогда, когда пользователь пытается открыть страницу, для доступа к которой сначала надо осуществить вход в систему. Если у вас есть профиль, просто войдите в него и попробуйте вновь загрузить нужную страницу.
  • Если вы заходите со смартфона, попробуйте отключить функцию экономии трафика в браузере. Она находится в настройках, в мобильном Google Chrome под нее отведен отдельный раздел. 
  • Последний шаг – подождать. Когда ни один способ не помогает, значит, неполадки возникли именно на сайте. Возможно, его владелец уже ищет способы решения проблемы и приступает к их исполнению, но это может занять какое-то время. Пользователям остается только дождаться, когда все работы будут завершены.

Еще одна допустимая причина появления ошибки сервера 403 – доступ к сайту запрещен для определенного региона или страны, в которой вы находитесь. Бывает и такое, что сайт доступен для использования только в одной стране. Если вы используете VPN, попробуйте отключить его и перезагрузите страницу. Вдруг получится все исправить. 

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

«Четырёхсотые» коды состояния описывают проблемы на стороне клиента: обычно они возникают, когда браузер отправляет серверу некорректный HTTP-запрос.

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

  • Что означает ошибка 403 (Forbidden)
  • Что могло пойти не так
  • Ошибки на стороне пользователя
  • Ошибки на стороне сайта
  • Ограничения на стороне хостера или провайдера
  • Как исправить ошибку 403
  • Что делать владельцу сайта
  • Что делать пользователю

Ошибка 403 (Forbidden) — это когда сервер понял запрос, но почему-то отказывается выполнять его и отдавать браузеру HTML-код страницы.

Помимо «Forbidden», сервер может описать ошибку и другими словами: «error access denied» (доступ запрещён), «you don’t have permission to access» (нет разрешения на вход) и так далее. Сообщения разные, но смысл один.

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

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

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

Неправильный URL-адрес. Возможно, вы случайно постучались на какую-то секретную страничку, а это ни вам, ни серверу не нужно. Банально, но стоит перепроверить ссылку ещё разок.

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

  • Неправильные данные в кэше. Тогда можно почистить его или перезагрузить страницу сочетанием Ctrl + F5 (при таком принудительном обновлении кэш игнорируется).
  • Устаревшие данные в cookies. Если проблема в этом, то достаточно почистить их, и всё заработает.
  • Вы заходите на страницу со смартфона, на котором включён режим экономии трафика. Из-за него браузер может не передавать сайту какие-то нужные ему данные — это и вызывает HTTP-ошибку Forbidden. В этом случае достаточно отключить экономию трафика.

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

Кадр: сериал «Парки и зоны отдыха» / NBC

«Forbidden» может возникнуть, если что-то не так с компонентами сайта. Вот несколько возможных проблем, которые может и должен решить администратор сайта.

Некорректный индексный файл. Это файл, который указывает на главную страницу домена или поддомена. Нужно, чтобы у него были правильное название и формат — а они, в свою очередь, определяются CMS, которой вы пользуетесь. Например, для сайтов на WordPress это может быть index.html, index.htm или index.php.

А ещё индексный файл должен находиться в корневой папке домена или поддомена — смотря к чему он относится.

Неправильно расположены файлы сайта. Как и index, другие файлы сайта тоже должны лежать в корневой директории. Где именно — зависит от CMS и хостинга, которые вы используете.

Неверно настроены права доступа. У каждого файла и папки есть права доступа, которые состоят из трёх цифр от 0 до 7: первая — права владельца, вторая — групповые права, третья — публичные права. Сама цифра означает, какие права предоставлены этой группе.

Если у пользователя нет прав на выполнение действия, то он получит HTTP-ошибку 403 Forbidden. Обычно на папки выставляют доступ 755, на файлы — 644.

Проблемы с плагином. Если вы устанавливали плагины для своей CMS, то вызвать код 403 может какой-то из них. Возможно, он не обновился до последней версии, повреждён или несовместим с конфигурациями сайта.

Вот как это проверить, если у вас WordPress:

  • Перейдите в раздел wp-content и найдите папку plugins.
  • Переименуйте её — это отключит работу всех плагинов.
  • Если проблема уйдёт, значит, дело было в плагинах.

Далее можно включать плагины обратно и искать конкретного виновника. Чтобы это сделать, отключайте их по очереди и обновляйте страницу — где-то по пути точно обнаружите, где с каким плагином проблема.

Некорректные указания в файле .htaccess. Если вы используете Apache Web Server, попробуйте переименовать файл .htaccess. Так же как и с плагинами, это отключит его и позволит понять, виновен ли он в ошибке.

Если дело всё-таки в .htaccess, проверьте и исправьте его директивы. Вот на какие условия стоит обратить внимание:

  • deny (запрещает доступ);
  • allow (разрешает доступ);
  • require (запрещает или разрешает доступ всем, кроме указанных пользователей);
  • redirect (перенаправляет запрос на другой URL);
  • RewriteRule (преобразует строку с помощью регулярных выражений).

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

Чтобы проверить, в этом ли дело, отключите брандмауэр и повторите запрещённое действие. Если сработает — проблема найдена. Проверьте журнал брандмауэра: там должна быть указана конкретная причина блокировки запроса.

Узнав причину, добавьте её в исключения, и такие запросы будут выполняться корректно.

Тариф хостинга не поддерживает инструменты. Например, вы пишете на PHP 8, а тариф рассчитан только на PHP 7.4. В таком случае придётся либо перейти на другую версию инструмента, либо сменить тариф (а может, и целого хостера).

Бывает так: с логикой на сервере всё в порядке, HTTP-запрос составлен корректно, а ошибка 403 всё равно возникает. Но подождите кричать «Тысяча чертей!» — возможно, шайба на стороне посредника.

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

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

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

Да-а, такая маленькая ошибка, а проблем — как с запуском Falcon Heavy на Марс. Держите чек-лист, который поможет не запутаться и быстро всё пофиксить.

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

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

Если ничего не помогает — обратитесь за помощью к своему хостинг-провайдеру.

  • Перепроверьте URL страницы: правильный ли он? Вы могли кликнуть по ошибочной ссылке или сайт переехал на другой адрес, а поисковики этого ещё не поняли.
  • Проверьте, авторизованы ли вы на сайте. Залогиньтесь, если есть такая возможность.
  • Зайдите на страницу с другого устройства. Если сайт заработал — проблема в устройстве. Попробуйте перезагрузить страницу, почистить кэш и cookies браузера или отключить экономию трафика.
  • Включите или выключите VPN. Возможно, доступ к сайту блокируется по IP-адресу для пользователей из определённой страны или региона. Попробуйте использовать IP-адреса разных стран.
  • Подключитесь к другой сети. Например, если пользуетесь 4G, перейдите на Wi-Fi. Это поможет понять, есть ли проблемы на стороне поставщика интернета.

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

403 Forbidden Error: What It Is and How to Fix It

Jun 22, 2022 7:41:27 AM |
403 Forbidden Error: What It Is and How to Fix It

A detailed explanation of what a 403 Forbidden Error response is, including troubleshooting tips to help you resolve this error.

The 403 Forbidden Error is an HTTP response status code that indicates an identified client does not have proper authorization to access the requested content. As with most HTTP response codes, a 403 Forbidden Error can be challenging to diagnose and resolve properly.

With a pool of over 50 potential status codes representing 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.

This article will examine the 403 Forbidden Error in more detail. We’ll look at what causes this message, along with a handful of tips for diagnosing and debugging 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 403 Forbidden Error. Let’s dive in!

Server- or Client-Side?

All HTTP response status codes in the 4xx category are considered client error responses. These messages contrast with errors in the 5xx category, such as the 502 Bad Gateway Error. 500 errors are considered server error responses.

That said, the appearance of a 4xx error doesn’t necessarily mean the issue has something to do with the client (the web browser or device used to access the application). Oftentimes, if you’re trying to diagnose an issue with your own application, you can ignore most client-side code and components. This includes HTML, cascading style sheets (CSS), client-side JavaScript, etc. This doesn’t apply just to websites, either. Behind the scenes, normal web applications power smartphone apps that use a modern-looking user interface.

Although the 403 Forbidden Error is considered a client error response, you shouldn’t rule out the server as the culprit. The server network object is producing the 403 Error and returning it as the HTTP response code to the client. On the other hand, this doesn’t rule out the client as the actual cause of a 403 Forbidden Error, either. The client might be trying to access an invalid URL, the browser could be failing to send the proper credentials to the site, and so forth. We’ll explore some of these scenarios (and potential solutions) below.

Start With a Thorough Application Backup

Before making changes to your application, make sure to back up your system. This might include a full backup of your application, database, and so forth.

If you have the capability, create a complete copy of the application onto a secondary staging server that isn’t «live» or available to the public. This will allow you to test all potential fixes without threatening the security of your live application.

Diagnosing a 403 Forbidden Error

As previously mentioned, many 403 Forbidden Errors involve the server denying authorization to a client (a web browser, in most cases) that has requested content.

This typically occurs in one of two scenarios:

  • The client sent its authentication credentials to the server and the server authenticated that the client was valid. Yet, the server rejected the authorized client from accessing the requested content for some reason.
  • The requested content is strictly forbidden for all clients, regardless of authorization. This occurs when attempting to access an invalid or forbidden URL that the web server software has restricted. For example, Apache servers return a 403 Forbidden Error when a client tries to access a URL corresponding to a file system directory.

Troubleshooting on the Client-Side

Since the 403 Forbidden Error is a client error response code, start troubleshooting any potential client-side issues first.

Here are some troubleshooting tips you can try on the browser or device that is giving you problems.

Check the Requested URL

The most common cause of a 403 Forbidden Error is simply inputting an incorrect URL. As discussed before, many tightly secured web servers disallow access to improper URLs. This could be anything from accessing a file directory to accessing a private page meant for other users. Thus, it’s a good idea to double-check the exact URL that is returning the 403 error.

Clear Relevant Cookies

As you may already be aware, HTTP copies store tiny pieces of data on your local device. The website then uses these cookies to to «remember» information abbot a particular browser and/or device.

As you may already be aware, HTTP cookies store tiny pieces of data on your local device. The website then uses these cookies to «remember» information about a particular browser and/or device. Most modern web apps take advantage of these cookies to store user authentication status.

Invalid or corrupted Cookies can cause improper authentication for the server, leading to the 403 Error. This is due to the fact that the client is no longer authenticated to perform this particular request.

In most cases, you should only worry about cookies relevant to the website or application causing issues. The application stores cookies based on where the domain is located. This means you can only remove cookies that match the website domain (e.g. airbrake.io) to keep most other cookies intact. However, if you aren’t experienced with manually removing certain cookies, remove all cookies at once. Not only is this easier, but it’s also a safer option.

Below, we’ve provided a list on how to clear cookies depending on the browser you’re using:

  • Google Chrome
  • Internet Explorer
  • Microsoft Edge
  • Mozilla Firefox
  • Safari

Clear the Cache

Just like cookies, it’s also possible that the local browser cache could be causing the 403 Forbidden Error to appear.

A cache stores local copies of web content on your device for later use. A browser’s cache can include almost any type of data but typically stores compressed snapshots of webpages, images, and other binary data your browser often accesses. With a local copy of these resources on your device, your browser doesn’t need to spend time or bandwidth downloading this identical data every time you return to the same page. For example, when you open Facebook, there’s a good chance that the content you’re seeing has come from the cache on your device.

Since your browser’s cache stores local copies of web content and resources, it’s possible that a change to the live version of your application is conflicting with the cached version already on your device, which can sometimes produce a 403 Forbidden Error as a result. Try clearing your browser’s cache to see if that fixes the issue.

As with cookies, clearing the cache is browser-dependant, so here are a few links to that relevant documentation for the most popular browsers:

  • Google Chrome
  • Internet Explorer
  • Microsoft Edge
  • Mozilla Firefox
  • Safari

Log Out and Log In

If the application you’re using has some form of user authentication, the last client-side step to try is to log out and then log back in. If you’ve recently cleared the browser cookies, this should usually log you out, so the next time you try to load the page, just log back in at this point.

In some situations, the application may be running into a problem with your previous session, which is just a string that the server sends to the client to identify that client during future requests. As with other data, your device should have stored the session token (or session string) locally on your device within the cookies. The client then transfers this data to the server during every request. If the server fails to recognize the session token or the server sees this particular token as invalid, this may result in a 403 Error.

But, with most web applications, you can recreate the local session token by logging out and logging back in.

Debugging Common Platforms

If you’re running common software packages on the server that is responding with the 403 Forbidden Error, you may want to start by looking into the stability and functionality of those platforms first. The most common content management systems (CMS) — 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 403 Error.

Here are a few tips to help you troubleshoot some of these popular software platforms:

Rollback Recent Upgrades

If you recently updated the CMS itself just before the 403 Forbidden 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 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.

Uninstall New Extensions, Modules, or Plugins

Depending on the particular CMS 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. 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, try uninstalling any recently added extensions. Again, Google the extension name for the official documentation and assistance with this process.

Check for Unexpected Database Changes

Uninstalling a CMS extension does not guarantee that changes will fully revert. This is particularly true for WordPress extensions. These extensions have carte blanche status within an application, which allows them full access rights to the database. With this access, an extension can modify database records that don’t «belong» to the extension itself. That means it can change records created and managed by other extensions of the 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. Your best course of action, assuming you’re reasonably convinced an extension is the likely culprit for the 403 Forbidden Error, is to open the database and manually look through tables and records that were likely modified by the extension.

Confirm Proper File Permissions

If the application worked fine before and suddenly this error occurs, permissions are not a very likely culprit. However, if modifications were recently made (such as upgrades or installations), it’s possible that file permissions were changed or are otherwise incorrect, which could cause an issue to propagate its way throughout the application and eventually lead to a 403 Forbidden Error. The majority of servers use Unix-based operating systems.

In this Wikipedia article, File-System Permissions, you’ll learn more about how to set up proper permissions for application files and directories to keep your application secure without hindering your applications’ access.

Above all, Google is your friend. Search for specific terms related to your issue, such as the name of your application’s CMS, along with the 403 Forbidden Error. Chances are you’ll find someone (or, perhaps, many someones) who have experienced this issue and have found a solution.

Troubleshooting on the Server-Side

If you’re confident that your CMS isn’t the problem, a 403 Error could be a result of a server-side issue.

Troubleshoot the server with these tips.

Check Your Web Server Configuration

Most modern web servers provide one or more configuration files to adjust server behavior. These configurations are based on a wide range of circumstances. For example, the server may be configured to reject requests to certain directories or URLs, which could result in a 403 Error.

Configuration options for each different type of web server can vary dramatically. Here is a list of a few popular ones to give you some resources to look through:

  • 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 contain the history of what the application did, such as which pages were requested, which servers it connected to, which database results it provided, and so forth. Server logs are related to the actual hardware that is running the application. They 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, for more information on finding the logs in question.

Check the Database for User Authentication

As you know now, a 403 Error may indicate that the client properly authenticated at some point, but doesn’t have access to the requested resource. It’s worth checking the server to see why it denied the requested resource. Perhaps there’s an issue with the database and can’t authenticate the client.

Verify Server Connectivity

While it may sound simple, it’s entirely possible that a Forbidden Error simply indicates that a server somewhere in the chain is down or unreachable for whatever reason. Most modern applications don’t reside on a single server. Instead, applications may be spread over multiple servers or rely on third-party services to function. If any one of these servers are down for maintenance or otherwise inaccessible, this could result in an error that appears to be from your own application.

Debug Your Application Code or Scripts

If all else fails, manually debug your application by 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. This will allow you to recreate the exact scenario in which the 403 Forbidden Error occurred and view the application code at the moment something goes wrong.

But, for a faster way to debug, install Airbrake Error & Performance Monitoring. If there’s broken code that’s throwing a 403 Error, Airbrake will find it, and quickly. Create a free Airbrake dev account, today, and for the first 30-days, you’ll have access to unlimited error and performance events.

Note: We published this post in October 2017 and recently updated it in February 2022.

Table of Contents

  • Introduction: What is a 403 Error?
  • 1. Firewall Rules
    – 403 on an Image or File
  • 2. Caching and Nonces
  • 3. File Permissions
  • 4. CDN Issues
  • 5. Corrupt/Misconfigured .htaccess file
  • 6. Missing WordPress Core Files
  • 7. Broken/Missing Plugins
  • 8. Custom Nginx Config Rules

Introduction: What is a 403 Forbidden Error?

The 403 Forbidden error occurs when a request is made the server cannot allow. This is often due to a firewall ruleset that strictly prohibits this specific request, but other settings such as permissions may prevent access based on user rights.

When 403s occur, your server understands the request that is being made, but is refusing to comply with the request. 

That’s about all there is to it. Your request is forbidden.

Error Messaging

On Nginx a 403 looks as follows: 403 Forbidden – nginx

Note: We published this post in October 2017 and recently updated it in February 2022.

Table of Contents

  • Introduction: What is a 403 Error?
  • 1. Firewall Rules
    – 403 on an Image or File
  • 2. Caching and Nonces
  • 3. File Permissions
  • 4. CDN Issues
  • 5. Corrupt/Misconfigured .htaccess file
  • 6. Missing WordPress Core Files
  • 7. Broken/Missing Plugins
  • 8. Custom Nginx Config Rules

Introduction: What is a 403 Forbidden Error?

The 403 Forbidden error occurs when a request is made the server cannot allow. This is often due to a firewall ruleset that strictly prohibits this specific request, but other settings such as permissions may prevent access based on user rights.

When 403s occur, your server understands the request that is being made, but is refusing to comply with the request. 

That’s about all there is to it. Your request is forbidden.

Error Messaging

On Nginx a 403 looks as follows: 403 Forbidden – nginx

Other variations of a 403 include:

  • 403 – Forbidden: Access is denied
  • Error 403 – Forbidden
  • 403 – Forbidden Error – You are not allowed to access this address
  • HTTP Error 403 – Forbidden – You do not have permission to access the document or program you requested
  • 403 Forbidden – Access to this resource on the server is denied


Note

The following are all certainly possibilities for your 403 errors, however, in 90% of cases, 403 errors are caused by a firewall, caching issue, or permissions issue.

Connecting to Your Servers

Some of the following may require you to SSH into your server. Don’t worry, almost anything you may need to do via SSH by following articles here in our knowledge base is the equivalent of basic HTML difficulty-wise. Please see these guides to get started:

1. Firewall Rules

By far the most common reason for 403 errors is that the request you’re making is being blocked for breaking one of the firewall rules.

Unlike most other hosting providers, GridPane equips you with 1-3 different Web Application Firewall (WAF) options depending on your plan: –

  1. 6G WAF
  2. 7G WAF
  3. ModSecurity

Usually, 403s are a good thing. In most cases, these types of requests are malicious in nature and the firewall blocks those from even reaching your application (WordPress website). However, WordPress is a vast ecosystem of different functionality and false positives can and do occur.

The quickest way to discover if your 403 error is being caused by a WAF is to simply turn it off and try to reproduce the issue. If the 403 no longer occurs, this is a WAF issue.

You can find out the specific reason the request is being blocked by checking the log. This is available directly inside the security tab at the bottom of the settings.

Once you know the cause, you can begin crafting an exclusion that is fairly straightforward, and fully documented in the links above.

Example

Here’s an example of a request that resulted in a 403 error with the 7G WAF:

website.com/wp-admin/admin.php?page=seopress-google-analytics&code=4/0AY0eSoaWlA&scope=https://www.googleapis.com/auth/analytics.readonly

This request broke 2 rules, as detailed by this result in the 7G WAF log:

[17/Nov/2020:15:05:35 +0000] [":bad_querystring_12::bad_request_15:"] 199.199.199.199 yourdomain.com "GET /wp-admin/admin.php?page=seopress-google-analytics&code=4/0AY0e-g44ZrE9024kffJQ2LbRdRxVLOQgAruyU9wAHI1jYFCDaUo10xmwW5rpilPzqNKOSoaWlA&scope=https://www.googleapis.com/auth/analytics.readonly HTTP/1.1" 403 "https://accounts.google.com/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"

Using this information we can create a rule to exclude these two results by targeting “page=seopress-google-analytics&code” and adding an exclusion for both errors like so:

set $exclusion_rule_match "";
if ( $args ~* ^page=seopress-google-analytics&code ) {
set $exclusion_rule_match 15;
}
if ($bad_request_7g = $exclusion_rule_match) {
set $7g_drop_bad_request 0;
}
set $exclusion_rule_match "";
if ( $args ~* ^page=seopress-google-analytics&code ) {
set $exclusion_rule_match 12;
}
if ($bad_querystring_7g = $exclusion_rule_match) {
set $7g_drop_bad_query_string 0;
}

Please see the full articles for a complete tutorial.

403 on an Image or File

Following on from the above section, images or files may sometimes return a 403 for a seemingly unknown reason.

These can be difficult to troubleshoot because it’s really not obvious what the cause is, however, this is almost certainly

A couple of examples to illustrate this are images/files that contain either the word “Specialist” or the word “Conference”. 

The reason these get flagged are due to the word conference containing “conf” (which is a file name extension), and specialist containing the name of a commonly spammed pharmaceutical.

The quickest solution is to rename the file, or to edit out that specific line or word in the firewall. Our documentation has details how to do this here:

Using the GridPane 7G Web Application Firewall

2. Caching and Nonces

The second most common issue outside of a firewall rule being is broken is where caching is interfering with a form (such as a contact form, or payment gateway form). Here, the form uses what’s called a “nonce” (a security token which is a number or random string used only once), which exists for a set period of time (12 hours is common) after which it changes to something new. Once change occurs, the cache may serve the outdated nonce and this results in an error.

If you have a form or any functionality that makes use of a nonce, these can break and return 403 errors if the cache isn’t cleared once the nonce expires.

In many cases, nonces last 12-24 hours. For example, the Gravity forms payment gateway has a 12-hour nonce and can result in 403 errors if cached for over 12 hours.

If clearing the cache allows your functionality to begin operating correctly again, this is a caching issue.

Plugins we know of that may experience cache related issues are:

  1. Gravity Forms Payments
  2. Divi Forms
  3. Caldera Forms

In these cases, there are a couple of different solutions.

Solution 1. Exclude the page from the cache

If you exclude the page from the cache, the cache will not interfere with the nonce and all forms will operate as normal. 

Please see the following guide on how to exclude a page from your website’s cache (Nginx only):

Exclude a page from server caching

Solution 2. Reduce Cache TTL

If you’re using Redis Page Caching, the default TTL is 30 days. If you’re experiencing nonce related form failures, you can reduce the cache time to avoid these in the future.

This requires running a single GP-CLI command. To do so, you will need to SSH into your server. Please see the following guides to get started:

The command for altering the default caching TTL is as follows:

gp stack nginx redis -site-cache-valid {accepted.value} {site.url}

Run the following command to reduce cache time to 6 hours (replacing site.url with your domain name):

gp stack nginx redis -site-cache-valid 21600 site.url

The time length has to be entered in seconds. In this case, 6 hours = 21600 seconds.

For 10 hours, run the following:

gp stack nginx redis -site-cache-valid 36000 site.url

For more details, please see this Redis Page caching section in the Configure Nginx article:

Set caching expiry time for all successful requests going into Redis SRCache page cache

3. Permissions

403 errors can also be caused by incorrect permissions settings. This can sometimes occur when migrating a website over to GridPane.

Fortunately, we have a quick fix self-help tool that can help reset your website to the correct permissions very quickly and with minimal fuss. To fix your websites permissions, please see this article:

Self Help Tools: Reset Application File Permissions

4. CDN Issues

If the 403 forbidden errors you’re experiencing are specific to your assets (images, CSS, and JS files), and you’re using a delivery network (CDN) for your website, try temporarily disabling this service to see if this is at the root of your issue.

If it isn’t, this is likely firewall related, possibly due to 7G Bad Bot rule #5.

5. Corrupt/Misconfigured .htaccess File

Nginx doesn’t use .htaccess, so this error is OpenLiteSpeed specific for GridPane hosted websites.

This is a very powerful file, and if corrupted or misconfigured, this could result in a 403 error for your website.

Fortunately, GridPane keeps a backup copy that you can use in the case of an emergency:

You can get your website back up and running by replacing the current .htaccess file with the contents of the .htaccess.save file.

This is easier done over SFTP. To connect to your server over SFTP, please see either one of the following articles:

Connect to a GridPane Server by SFTP as System User

Connect to a GridPane Server by SFTP as Root user

Step 1

Once connected, first save a copy of the .htaccess.save file to your computer.

Step 2

Next, rename the corrupt .htaccess file to .htaccess.bad

Step 3

Next, rename .htaccess.save to .htaccess and then check your website.

Step 4

You can now re-upload the .htaccess.save to your server again for safekeeping, and delete the .htaccess.bad file.

6. Missing WordPress Core Files

If there are missing Core WordPress files on your site, or if one has been moved to another directory for some reason (I can recall one case where a client had decided to move their wp-settings.php file outside of htdocs, then created an emergency support ticket without any details of what they’d just done).

This may result in either a 403 or a 500 error. The previous section above contains a list of the files inside htdocs – note that those that begin with a “.” are hidden files.

You can run a check with the following command (replace site.url with your domain name):

gp wp site.url core verify-checksums

For example:

gp wp yourwebsite.com core verify-checksums

This will check your core WordPress installation files and let you know if any issues need to be addressed. 

This type of issue is usually the result of malware.

7. Broken/Missing Theme or Plugin Files

If none of the above is the cause for your 403 error, then this could be the work of a broken or missing plugin file.

To check, connect to your server over SFTP (see the links in part 5 above to get started) and rename the plugins folder (located at site.url/htdocs/wp-content/plugins) to plugins-off.

Next, check your website and see if the 403 error is occurring. If not, then you know the root cause is one of the plugins on your website.

Rename the plugins-off directory back to plugins, and then do the same for each of your individual plugin folders, renaming them one by one until you find the one responsible.

8. Custom Nginx Configurations

Sometimes plugin authors can be rather careless with their Nginx recommendations, documenting broad Nginx rules that can result in unexpected/undesirable behavior such as blocking specific types of files altogether, or blocking them when not logged into the website.

You may have added custom configuration rules to Nginx via .conf files in your  /var/www/site.url/nginx directory.

For example:

/var/www/example.com/nginx/ithemes-security-main-context.conf

Custom configurations that affect ALL websites on the server may also have been added in these directories:

/etc/nginx/extra.d/
/etc/nginx/conf.d/

Be sure to check this directory for any Nginx configuration files that you or your team members may have added (be sure to ask them so you know what to look for), and review them for code that could prevent access to page or file that your getting your 403 forbidden error.

HTTP Error 403 Forbidden: What It Means and How to Fix It

Receiving any error code while online can be a frustrating experience. While we’ve become accustomed to 404 Not Found pages, even to the extent that it’s become common to see cute placeholder pages to entertain us whenever we get lost, one of the more puzzling errors is the 403: Forbidden response.

What does it mean?

Simply put: the server has determined that you are not allowed access to the thing you’ve requested.

According to RFC 7231:

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it…If authentication credentials were provided in the request, the server considers them insufficient to grant access.

The 403 response belongs to the 4xx range of HTTP responses: Client errors. This means either you, or your browser, did something wrong.

If you encounter this it usually means that you have already authenticated yourself with the server, i.e. you’ve logged in, but the resource you have requested expects someone with higher privileges.

Most commonly, you might be logged in as a standard user, but you are attempting to access an admin page.

How do you fix it?

As a user without access to the server, you really only have a few options:

Authenticate yourself with a more appropriate account

Again, according to RFC 7231:

If authentication credentials were provided in the request, the server considers them insufficient to grant access.  The client SHOULD NOT automatically repeat the request with the same credentials.  The client MAY repeat the request with new or different credentials.

This is the only one that gives you any immediate power to rectify the issue.

If you have multiple accounts for a site and you are attempting to do something you can usually do, but this time are forbidden from doing, this is the option you should try. Log in with your other account.

You may find that this option also requires clearing your cache or cookies, just in case logging in as another user doesn’t sufficiently flush the previous authentication tokens. But this is usually unnecessary.

As a desperate move, you could also try disabling browser extensions that might be interfering with your use of the site. However, this is unlikely, since a 403 implies you are authenticated, but not authorized.

Notify the site owner that a 403 is being returned when you’d expect otherwise

If you fully expect that you should be able to access the resource in question, but you are still seeing this error, it is wise to let the team behind the site know — this could be an error on their part.

Once more from RFC 7231:

However, a request might be forbidden for reasons unrelated to the credentials.

A common cause for this happening unintentionally can be that a server uses allow- or deny-lists for particular IP addresses or geographical regions.

They might have a good reason for blocking your access outside of their strictly defined parameters, but it could also just be an oversight.

Give up.

Maybe you just aren’t supposed to be able to access that resource. It happens. It’s a big internet and it’s reasonable to expect that there are some areas off limits to you personally.

You could visit http.cat instead while ruminating on why your original request was forbidden.


As a reader of freeCodeCamp News, you are almost certainly not forbidden from following @JacksonBates on Twitter for more tech and programming related content.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Ошибка this operating system is not supported
  • Ошибка this method is not allowed for anonymous call
  • Ошибка this is xray engine
  • Ошибка this is not exe you are looking for
  • Ошибка the dynamic library gsrld dll failed to load