Permission Denied: How to Find the Problem in the Path and Access Rights
Use namei and stat to check the entire file path, owner, and access mode before changing the site directory permissions.

In this article
Файл существует, но приложение получает отказ в доступе. Частая ошибка — сразу разрешить всё всем. Это может скрыть исходную причину и открыть данные посторонним. Сначала нужно установить, какой пользователь обращается к файлу и на каком участке пути доступ прекращается.
Проверьте каждый каталог в пути
Примеры подходят для Linux с util-linux и GNU Coreutils. Путь /var/www/site/config.php условный: замените его на реально проблемный файл, не выводя его содержимое.
namei -l /var/www/site/config.php
Команда показывает компоненты пути, их типы, владельцев и права. Для прохода к файлу нужны подходящие разрешения на родительские каталоги. Поэтому исправные права самого файла не помогают, если один из каталогов выше недоступен пользователю процесса.
Обратите внимание на символические ссылки. Фактическая цель может находиться в другом месте с другими правилами. Проверять нужно путь, который реально использует приложение, а не похожий файл в копии проекта.
Прочитайте метаданные объекта
Для отдельного файла:
stat /var/www/site/config.php
По умолчанию GNU stat описывает саму символическую ссылку, если указанная запись является ссылкой. Для следования к её цели используется -L. Не смешивайте эти два результата при сравнении владельца и режима.
Посмотрите владельца, группу и права, затем сопоставьте их с пользователем рабочего процесса. Пользователь вашего терминала может иметь доступ, которого нет у PHP или фонового задания. Успешное чтение из личного сеанса не подтверждает доступ приложения.
Обычных прав бывает недостаточно
Если режим выглядит подходящим, проверьте ACL и политики безопасности, применяемые в вашей системе. Доступ также может ограничиваться контейнером, пространством монтирования или настройками службы. Не отключайте такие механизмы ради проверки без понимания конкретного отказа.
Пример: после переноса проекта файл принадлежит пользователю, которого нет в рабочей схеме нового сервера. Исправление должно вернуть ожидаемую модель владения. Массовое назначение одинаковых прав всем файлам не учитывает различие между каталогами, публичными ресурсами и конфигурацией с секретами.
Уточните тип операции
Чтение существующего файла, создание нового файла и замена через временный файл требуют разных разрешений. Приложение может успешно читать конфигурацию, но не иметь права создать временную запись в каталоге. Поэтому в отчёте важно указать не только путь, но и выполняемую операцию.
Не помещайте пароль или содержимое ключа в диагностический вывод. Для первого этапа обычно достаточно имени процесса, обезличенного пути, владельца, группы и режима. Если проблема касается конфигурации с секретами, само содержимое файла читать не требуется.
Проверьте точечное исправление
После согласованного изменения повторите исходную операцию от имени приложения и заново посмотрите метаданные. Убедитесь, что заработал нужный сценарий, а доступ не расширился лишним пользователям. Хорошее исправление объясняет, почему конкретный процесс получил необходимое разрешение. Оно не сводится к исчезновению ошибки после рекурсивного открытия всего каталога.
The file exists, but the application receives a permission denied error. A common mistake is to immediately grant access to everyone. This can hide the root cause and expose data to unauthorized users. First, determine which user is accessing the file and where in the path access is blocked.
Check every directory in the path
The examples apply to Linux with util-linux and GNU Coreutils. The path /var/www/site/config.php is conditional: replace it with the actual problematic file without outputting its contents.
namei -l /var/www/site/config.php
The command displays path components, their types, owners, and permissions. To access the file, appropriate permissions are required on parent directories. Therefore, correct permissions on the file itself do not help if one of the higher-level directories is inaccessible to the process user.
Pay attention to symbolic links. The actual target may be located elsewhere with different rules. You must check the path that the application actually uses, not a similar file in a project copy.
Read the object metadata
For a single file:
stat /var/www/site/config.php
By default, GNU stat describes the symbolic link itself if the specified entry is a link. To follow to its target, use -L. Do not mix these two results when comparing owner and mode.
Check the owner, group, and permissions, then map them to the workflow user. The terminal user may have access that PHP or the background job lacks. Successful reading in a personal session does not confirm application access.
Standard permissions may be insufficient
If the mode looks appropriate, check the ACLs and security policies applied in your system. Access may also be restricted by the container, mount namespace, or service settings. Do not disable such mechanisms for testing without understanding the specific failure.
Example: after migrating a project, the file is owned by a user who does not exist in the new server's working scheme. The fix must restore the expected ownership model. Mass-assigning identical permissions to all files ignores the distinction between directories, public resources, and configuration with secrets.
Clarify the operation type
Reading an existing file, creating a new file, and replacing via a temporary file require different permissions. An application may successfully read configuration but lack the right to create a temporary record in the directory. Therefore, the report must specify not only the path but also the operation being performed.
Do not include passwords or key contents in diagnostic output. For the first stage, the process name, anonymized path, owner, group, and mode are usually sufficient. If the issue involves a configuration with secrets, reading the file contents is not required.
Check the patch
After the agreed change, repeat the original operation on behalf of the application and re-examine the metadata. Ensure the intended scenario works and access has not been expanded to unnecessary users. A good fix explains why a specific process received the necessary permission. It is not merely the disappearance of an error after recursively opening the entire directory.

Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.