mod_wsgi虚拟环境启动PermissionError问题求助
错误信息
[Fri Apr 14 16:49:46.261165 2023] [wsgi:error] [pid 76114:tid 139906982557248] [client 91.23.91.105:60033] mod_wsgi (pid=76114): Failed to exec Python script file '/var/www/conjugationgame.de/init.wsgi'., referer: https://conjugationgame.de/
[Fri Apr 14 16:49:46.261252 2023] [wsgi:error] [pid 76114:tid 139906982557248] [client 91.23.91.105:60033] mod_wsgi (pid=76114): Exception occurred processing WSGI script '/var/www/conjugationgame.de/init.wsgi'., referer: https://conjugationgame.de/
[Fri Apr 14 16:49:46.261396 2023] [wsgi:error] [pid 76114:tid 139906982557248] [client 91.23.91.105:60033] Traceback (most recent call last):, referer: https://conjugationgame.de/
[Fri Apr 14 16:49:46.261438 2023] [wsgi:error] [pid 76114:tid 139906982557248] [client 91.23.91.105:60033] File "/var/www/conjugationgame.de/init.wsgi", line 4, in , referer: https://conjugationgame.de/
[Fri Apr 14 16:49:46.261445 2023] [wsgi:error] [pid 76114:tid 139906982557248] [client 91.23.91.105:60033] with open(activate_this) as file_:, referer: https://conjugationgame.de/
[Fri Apr 14 16:49:46.261464 2023] [wsgi:error] [pid 76114:tid 139906982557248] [client 91.23.91.105:60033] PermissionError: [Errno 13] Permission denied: '/home/hfwds/.local/share/virtualenvs/conjugationgame-4RgIZZXj/bin/activate_this.py', referer: https://conjugationgame.de/
解决方案
1. 修复虚拟环境目录的完整权限链
仅设置/home/hfwds为755权限不够,Linux中目录的执行权限才允许用户进入并遍历目录,需要确保从根目录到activate_this.py的每一层路径都开放权限:
chmod 755 /home/hfwds/.local chmod 755 /home/hfwds/.local/share chmod 755 /home/hfwds/.local/share/virtualenvs chmod 755 /home/hfwds/.local/share/virtualenvs/conjugationgame-4RgIZZXj chmod 755 /home/hfwds/.local/share/virtualenvs/conjugationgame-4RgIZZXj/bin
同时确保目标文件本身可读:
chmod 644 /home/hfwds/.local/share/virtualenvs/conjugationgame-4RgIZZXj/bin/activate_this.py
2. 验证运行用户的权限
切换到Apache运行用户hfwds,直接读取目标文件确认权限是否生效:
su - hfwds cat /home/hfwds/.local/share/virtualenvs/conjugationgame-4RgIZZXj/bin/activate_this.py
如果此步骤报错,说明权限问题未彻底解决,需检查目录的用户组归属。
3. 替代方案:迁移虚拟环境到公共目录
若用户私有目录的权限限制难以绕过,可将虚拟环境迁移到Apache默认有权限访问的目录(如/var/www):
- 导出当前虚拟环境依赖:
pipenv run pip freeze > requirements.txt
- 删除原虚拟环境:
pipenv --rm
- 切换到项目目录重新创建虚拟环境:
cd /var/www/conjugationgame.de pipenv install --ignore-pipfile -r requirements.txt
- 更新
__init__.wsgi中的activate_this路径(用pipenv --venv获取新路径)。
4. 确认Apache配置正确性
确保Apache配置文件中已正确设置运行用户和组:
User hfwds Group hfwds
重启Apache使配置生效:
sudo systemctl restart apache2
5. 修复项目目录权限
针对之前创建虚拟环境时出现的/var/www目录权限错误,设置项目目录的归属:
sudo chown -R hfwds:hfwds /var/www/conjugationgame.de
内容的提问来源于stack exchange,提问作者Harald F

