在生产服务器上使用 django 登录时出现 Apache WSGI 权限错误

Apache WSGI permission error using django logging on production server

这是一些软件信息

Django 1.8.1 阿帕奇2 软呢帽 21

error_log输出

mod_wsgi (pid=8272): Target WSGI script '/var/www/anime/anime/wsgi.py' cannot be loaded as Python module.
mod_wsgi (pid=8272): Exception occurred processing WSGI script '/var/www/anime/anime/wsgi.py'.
Traceback (most recent call last):
   File "/usr/lib64/python3.4/logging/config.py", line 557, in configure
     handler = self.configure_handler(handlers[name])
   File "/usr/lib64/python3.4/logging/config.py", line 725, in configure_handler
     result = factory(**kwargs)
   File "/usr/lib64/python3.4/logging/__init__.py", line 999, in __init__
     StreamHandler.__init__(self, self._open())
   File "/usr/lib64/python3.4/logging/__init__.py", line 1023, in _open
     return open(self.baseFilename, self.mode, encoding=self.encoding)
 PermissionError: [Errno 13] Permission denied: '/var/www/anime/log/info.log'

 During handling of the above exception, another exception occurred:
 Traceback (most recent call last):
   File "/var/www/anime/anime/wsgi.py", line 16, in <module>
     application = get_wsgi_application()
   File "/opt/virtualenvs/django_project/lib64/python3.4/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application
     django.setup()
   File "/opt/virtualenvs/django_project/lib64/python3.4/site-packages/django/__init__.py", line 17, in setup
     configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
   File "/opt/virtualenvs/django_project/lib64/python3.4/site-packages/django/utils/log.py", line 86, in configure_logging
     logging_config_func(logging_settings)
   File "/usr/lib64/python3.4/logging/config.py", line 789, in dictConfig
     dictConfigClass(config).configure()
   File "/usr/lib64/python3.4/logging/config.py", line 565, in configure
     '%r: %s' % (name, e))
 ValueError: Unable to configure handler 'file': [Errno 13] Permission denied: '/var/www/anime/log/info.log'

这是文件的权限掩码

drwxrwxrwx. 2 apache apache 21 May 28 15:22 .
drwxr-xr-x. 6 apache apache 90 May 28 14:53 ..
-rwxrwxrwx. 1 apache apache  0 May 28 15:22 info.log

我已经在 SOF 中搜索了所有可能的解决方案,其中 none 可行。因此我怀疑它与 SELinux 设置有关?如果是,有人可以告诉我我需要将哪个标志设置为 true 吗?

在阅读了 SELinux 之后,我找到了这个权限错误的解决方案。我希望它能帮助其他在 RHEL 下的生产服务器上部署时遇到类似情况的人 linux.

基本上运行 命令 ls -Z 显示以下内容

drwxr-xr-x. apache apache unconfined_u:object_r:httpd_sys_content_t:s0 log

该文件夹标有 httpd_sys_content_t,这不允许 httpd 对该文件夹具有写入权限。因此我们需要将此标签更改为 httpd_sys_rw_content_t

首先,我们需要向 fcontext 添加一个条目,以告知 SELinux 将在此文件夹中创建的文件的默认标签是什么。

sudo semanage fcontext -a -t httpd_sys_rw_content_t "/path/to/directory(/.*)?"

这将向 fcontext 文件添加一个条目 (/etc/selinux/targeted/contexts/files/file_contexts.local)

接下来我们需要使用restorecon更新文件夹中所有文件的标签。

sudo restorecon -R -v /path/to/directory

现在与 django 日志记录相关的权限错误将从 httpd 中消失 error_log =)