«Четырёхсотые» коды состояния описывают проблемы на стороне клиента: обычно они возникают, когда браузер отправляет серверу некорректный 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 возникает правомерно. Например, если вы были заблокированы на сайте или пытаетесь получить доступ к служебной странице. В таком случае обратитесь к владельцу сайта, чтобы он снял бан или выдал нужные права.
«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. Это поможет понять, есть ли проблемы на стороне поставщика интернета.
Если ничего не помогает, значит, проблема на стороне сайта. Обратитесь в техподдержку и сообщите об ошибке — возможно, о ней ещё никто не знает.
From Wikipedia, the free encyclopedia
HTTP 403 is an HTTP status code meaning access to the requested resource is forbidden. The server understood the request, but will not fulfill it.
Specifications[edit]
HTTP 403 provides a distinct error case from HTTP 401; while HTTP 401 is returned when the client has not authenticated, and implies that a successful response may be returned following valid authentication, HTTP 403 is returned when the client is not permitted access to the resource despite providing authentication such as insufficient permissions of the authenticated account.[a]
Error 403: «The server understood the request, but is refusing to authorize it.» (RFC 7231)[1]
Error 401: «The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials.» (RFC 2616)[2]
The Apache web server returns 403 Forbidden in response to requests for URL[3] paths that corresponded to file system directories when directory listings have been disabled in the server and there is no Directory Index directive to specify an existing file to be returned to the browser. Some administrators configure the Mod proxy extension to Apache to block such requests and this will also return 403 Forbidden. Microsoft IIS responds in the same way when directory listings are denied in that server. In WebDAV, the 403 Forbidden response will be returned by the server if the client issued a PROPFIND request but did not also issue the required Depth header or issued a Depth header of infinity.[3]
Substatus error codes for IIS[edit]
The following nonstandard codes are returned by Microsoft’s Internet Information Services, and are not officially recognized by IANA.
- 403.1 – Execute access forbidden
- 403.2 – Read access forbidden
- 403.3 – Write access forbidden
- 403.4 – SSL required
- 403.5 – SSL 128 required
- 403.6 – IP address rejected
- 403.7 – Client certificate required
- 403.8 – Site access denied
- 403.9 – Too many users
- 403.10 – Invalid configuration
- 403.11 – Password change
- 403.12 – Mapper denied access
- 403.13 – Client certificate revoked
- 403.14 – Directory listing denied
- 403.15 – Client Access Licenses exceeded
- 403.16 – Client certificate is untrusted or invalid
- 403.17 – Client certificate has expired or is not yet valid
- 403.18 – Cannot execute request from that application pool
- 403.19 – Cannot execute CGIs for the client in this application pool
- 403.20 – Passport logon failed
- 403.21 – Source access denied
- 403.22 – Infinite depth is denied
- 403.502 – Too many requests from the same client IP; Dynamic IP Restriction limit reached
- 403.503 – Rejected due to IP address restriction
See also[edit]
- List of HTTP status codes
- URL redirection
Notes[edit]
- ^ See #403 substatus error codes for IIS for possible reasons of why a webserver may refuse to fulfill a request.
References[edit]
- ^
Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content. IETF. sec. 6.5.3. doi:10.17487/RFC7231. RFC 7231. - ^ Nielsen, Henrik; Mogul, Jeffrey; Masinter, Larry M.; Fielding, Roy T.; Gettys, Jim; Leach, Paul J.; Berners-Lee, Tim (June 1999). «RFC 2616 — Hypertext Transfer Protocol — HTTP/1.1». Tools.ietf.org. doi:10.17487/RFC2616. Retrieved 2018-04-09.
- ^ a b «HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)». IETF. June 2007. Archived from the original on March 3, 2016. Retrieved January 12, 2016.
External links[edit]
- Apache Module mod_proxy – Forward
- Working with SELinux Contexts Labeling files
- Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content
Imagine this – you’ve recently created a new website to host your content, and you’re excited to see it go live. You can’t wait to dive into SEO and begin ranking for keywords and attracting an audience to your brand.
But then a friend emails you and says, «Hey, is there a reason I see this when I click on your website? «
Image Source
Undoubtedly, a «403 Forbidden» message is cause for immediate concern. How many potential viewers are you losing, as they come across your website to find this message?
Fortunately, there are a few quick-and-easy solutions to a 403 error. Here, we’ll explain the top three, so you can get your site up and running.
A 403 Forbidden error is an HTTP status code sent to users by an HTTP server when a user tries to access a restricted URL. It means the page you were trying to reach is forbidden for one of two reasons: Either there is a removal or restriction of access permissions from the client-side, or there’s an accidental misconfiguration of the web server.
What you’ll typically see when you land on a page with a 403 forbidden error is something like this: «You don’t have authorization to view this page – HTTP Error 403.»
It can also have slightly different wording, like the example below.
Image Source
Wondering about the difference between a 403 and 404 error? Here it is: A 404 error happens when you access a page that no longer exists or cannot be found. A 403 error, on the other hand, indicates that your access has been denied due to incorrect credentials.
An easy way to remember it: 403 says «access denied» while 404 says «We can’t find what you asked for.»
What causes a 403 error?
There are a few reasons why you may see a 403 forbidden error. Here are the most common:
- Permission or ownership error – Permissions are represented by codes, which indicate what each type of user can do. If you have the incorrect code associated with a file or directory then your users may run into a 403 error.
- Wrong file or folder location – When uploading content to your site, you may have added it to the wrong directory, which is not accessible to your end-users.
- No index page – If your homepage doesn’t have an index page, it will not display correctly on a browser.
- Misconfigured WordPress plugin – A plugin may be blocking IP addresses to avoid malware, causing the 403 forbidden error.
Now that you know the causes, let’s address how to fix them.
How to Fix 403 Errors
1. Set the correct file permissions.
If you’ve configured your web server, you’ll want to add the server to the www-data group, and set ownership of /var/www to the www-data user and www-data group.
Then, make sure your directories are set to 755, your files are set to 644, and your dynamic content is set to 700. This determines which user types (owner, group, everyone) can read, write, and execute.
2. Make sure you have an index page.
Your website’s home page must be called index.html or index.php – if it’s not, you should rename the homepage to include one of those URL names.
Alternatively, you can upload an index page to your httpdocs directory and then set up a redirect on the index page to your real homepage.
3. Upload your website content to the correct directory on your server.
You might see a 403 forbidden message if you haven’t correctly uploaded your content to the directory on your server.
There are several different FTP clients you might’ve chosen to host your domain — let’s say you chose FileZilla, which is free and available for Windows, Mac, and Linux.
To publish your content online, you’ll need to put your files into the public/htdocs directory.
Note: If you’re using FileZilla, these instructions will vary if you use a different FTP client. Once you’ve dragged and dropped your files into the directory, you should search your website’s URL to double-check they now appear online.
If you’re in your FTP server and don’t see the httpdocs directory, you can create a file within the directory with this title, which could also solve the issue.
4. Deactivate and reactivate your plugins.
If you suspect one of your plugins is responsible for the 403 forbidden error, temporarily deactivate all of your plugins.
You may have noticed the error shortly after installing a plugin. If so, start with that one and work your way down from the most recent installation to the oldest.
Then, one by one, activate each plugin and refresh the page to determine which plugin is causing the error.
As you can see, 403 errors can typically be resolved in just a few easy steps. It’s just about knowing where to look.
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.
Ошибка сервера 403 (Forbidden Error) означает, что вам запрещен доступ к странице, файлу или папке, URL которых вы ввели в адресной строке. Причин может быть много:
- сайт заблокирован хостингом;
- на сайте есть ошибки конфигурации и настроек (неправильное расположение файлов, некорректные права доступа и так далее);
- на вас распространяются правила блокировки (по IP, географическому положению, отсутствию авторизации), выставленные на сайте;
- сайт запрещен в вашей стране и т. д.
Точно определить, что именно вызывает ошибку, сложно — в сообщении о ней обычно нет никакой полезной информации. Ниже мы описываем, что можно сделать для устранения ошибки 403 Forbidden в наиболее распространенных случаях.
Как исправить ошибку 403 владельцу сайта
Если вам поступают жалобы от посетителей сайта о 403 ошибке, прежде всего убедитесь, что ее причина не на стороне пользователя. Возможно, посетитель написал URL с ошибкой или находится в стране, в которой запрещен ваш сайт. Полный перечень причин смотрите в разделе «Что делать пользователю при появлении 403 ошибки».
Если причина все-таки в сайте, последовательно проверьте пункты ниже.
Расположение и имя индексного файла
Индексный файл открывается первым при обращении к сайту, и если сервер его не находит — выдается ошибка 403 forbidden. Проверьте, чтобы:
- файл назывался правильно. В зависимости от CMS это может быть index.php, index.html или index.htm;
- файл лежал в корневом каталоге или, если речь о поддомене — в корневом каталоге поддомена.
Права доступа
Если вы выставили неправильные права доступа на папку или файл, например, вместо «4» (чтение) поставили «0» (запрет доступа), то посетителю будет выдаваться ошибка сервера 403 Forbidden. Проверьте, какие права стоят в админке сайта:
- на папки стандартно должен быть доступ вида 755;
- на файлы — 644.
Уточните у разработчика сайта, какие права нужны для той папки или файла, по которой выдается 403 ошибка.
Плагины WordPress
На сайтах с CMS WordPress причиной ошибки с кодом 403 могут стать некорректно работающие плагины. Чтобы быстро проверить, в этом ли причина, сделайте следующее:
- С помощью панели управления хостингом или FTP найдите раздел wp-content.
- В нем вам понадобится директория plugins. Переименуйте папку, но так, чтобы вы потом могли найти ее и восстановить прежнее название.
- После переименования все плагины wordpress перестанут работать.
- Теперь откройте страницу, на которой появлялось сообщение о 403 ошибке. Если страница теперь нормально загружается, причина, скорее всего, в одном из плагинов.
- Переименуйте папку с плагинами обратно, после чего последовательно отключайте плагины по одному (можно таким же способом, как выше — переименовывая его папку) и проверяйте, исчезла ли после этого ошибка.
После того, как вы найдете плагин-виновник ошибки, попробуйте обновить его до последней версии. Если не поможет, придется его отключить или заменить другим
Другие причины ошибки 403
Иногда причиной появления ошибки сервера 403 может стать:
- Неправильное расположение файлов сайта. Например, вы могли при работе с FTP случайно перенести файлы из корневой папки во вложенную директорию. Проверьте, чтобы файлы располагались так, как требует CMS и структура хостинга.
- Неправильные настройки .htaccess (если на хостинге используется Apache-сервер). Переименуйте файл .htaccess, например, в .htaccess-старый, и он перестанет восприниматься сервером. Если после этого ошибка исчезла или изменился ее код — дело в директивах, прописанных в .htaccess. Исправить их поможет разработчик сайта или другой веб-программист.
- Блокировка сайта на уровне хостинга. Хостинг-провайдер может заблокировать сайт из-за нарушений договора, превышения ограничений по тарифу и других причин. Проверьте, получали ли вы соответствующее уведомление на почту.
- Блокировка по IP. Возможно, IP-адрес посетителя находится в списке заблокированных или не добавлен в список разрешенных для подключения. Такие ограничения обычно ставят на доступ к страницам админки сайта. Проверьте настройки доступа.
- Блокировка брандмауэром ModSecurity. Это ПО блокирует действия пользователей, которые считает вредоносными, и выдает в ответ на них 403 ошибку. Иногда ModSecurity ошибается и блокирует вполне добропорядочных посетителей. Добавьте в него исключение, если у вас VPS или выделенный сервер, или обратитесь с этой просьбой к хостеру, если сайт на виртуальном хостинге.
Что делать пользователю при появлении 403 ошибки?
Причина проблемы может находиться на стороне посетителя, а не сайта. Что может сделать пользователь, чтобы исправить ошибку сервера 403 forbidden:
- Проверить правильность URL. Причина может быть в элементарной опечатке.
- Обновить страницу с помощью Ctrl F5. Это действие — универсальная первая помощь при любых проблемах с отображением сайта в браузере. Возможно, какие-то неверные данные закешировались, а при обновлении по Ctrl F5 вы игнорируете кэш браузера и загружаете страницу с сайта напрямую. Можно также почистить кэш.
- Почистить cookie. В куках могут храниться устаревшие данные авторизации, которые сервер не принимает и отвечает ошибкой.
- Залогиниться на сайте. Возможно, папка или файл, которые вы хотите открыть, доступны только авторизованным пользователям, поэтому вам выдается ошибка 403 forbidden (нет доступа).
- Попробовать зайти через VPN. Ваш IP может быть заблокирован на сайте по какой-то причине. Блокировка может стоять и на все посещения из вашей страны или региона. Попробуйте зайти на сайт с IP-адресом другой страны.
- Проверить с другого устройства. Если на другом компьютере при попытке зайти на эту страницу вы также получаете ошибку с кодом 403 — скорее всего, проблема на самом сайте. Обратитесь к его владельцу.
- Отключите экономию трафика, если Error 403 появляется только на мобильном устройстве. Из-за этой функции сайт может не получать нужных для предоставления доступа данных, например, о вашем местоположении.
- Подождать и попробовать позже. Бывает, что сайт только что «переехал» на другой хостинг и настройки DNS просто не успели обновиться.
- Обратиться к провайдеру. Ошибка может быть связана с неверной конфигурацией его оборудования, внесением сайта в «черные списки» или выполнением запрещающих директив государственных органов.
Если вы попробовали все способы исправления, а ошибка 403 forbidden не исчезла, то ситуация, скорее всего, нетипичная. Обратитесь за помощью к техподдержке хостинг-провайдера или разработчику сайта.