Как обслуживать приложения Django с Apache и mod_wsgi на LXLE

Я пытаюсь обслуживать веб-страницы через Apache 2.4.18 из Django, используя mod_wsgi, и получаю ошибку 403 Forbidden при доступе к локальному хосту.

Система: LXLE Unix Apache 2.4.18 Django версии 1.11.17 libapache2-mod-WSGI-py3i

Выполненная процедура: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04

Симптомы:

  1. Перед изменением файла 000-default.conf страница Apache по умолчанию доступна по адресу localhost.
  2. После изменения файла 000-default.conf, как показано ниже, я получаю ошибку 403-Запрещено при доступе к адресу localhost.
  3. Если я запустил сервер Django, страница Django по умолчанию будет доступна по адресу localhost: 8000

Конфигурация: /etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf

    **#FROM HERE!!!**
    Alias /static /home/florian/django/myproject/myproject/static
    <Directory /home/florian/django/myproject/myproject/static>
        Require all granted
    </Directory>

    <Directory /home/florian/django/myproject/myproject/myproject/myproject>
        <Files wsgi.py>
           Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess myproject python-path=/home/florian/django/myproject python-home=/home/florian/django/myproject/myprojectenv
    WSGIProcessGroup myproject
    WSGIScriptAlias / /home/florian/django/myproject/myproject/myproject/wsgi.py


</VirtualHost>

Журнал ошибок Apache:

(myprojectenv) florian@desktop:~/django/myproject/myproject$ tail -n 10 /var/log/apache2/error.log
[Sun Dec 16 09:35:25.721695 2018] [authz_core:error] [pid 10317:tid 140256502339328] [client 127.0.0.1:54346] AH01630: client denied by server configuration: /home/florian/django/myproject/myproject/myproject/wsgi.py
[Sun Dec 16 09:44:33.817490 2018] [authz_core:error] [pid 10316:tid 140256510732032] [client 127.0.0.1:54504] AH01630: client denied by server configuration: /home/florian/django/myproject/myproject/myproject/wsgi.py
[Sun Dec 16 09:45:07.820025 2018] [authz_core:error] [pid 10316:tid 140256451983104] [client 127.0.0.1:54516] AH01630: client denied by server configuration: /home/florian/django/myproject/myproject/myproject/wsgi.py
[Sun Dec 16 09:52:32.657271 2018] [mpm_event:notice] [pid 10313:tid 140256727914368] AH00494: SIGHUP received.  Attempting to restart
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
[Sun Dec 16 09:52:32.718483 2018] [wsgi:warn] [pid 10313:tid 140256727914368] mod_wsgi: Compiled for Python/3.5.1+.
[Sun Dec 16 09:52:32.718498 2018] [wsgi:warn] [pid 10313:tid 140256727914368] mod_wsgi: Runtime using Python/3.5.2.
[Sun Dec 16 09:52:32.720846 2018] [mpm_event:notice] [pid 10313:tid 140256727914368] AH00489: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/3.5.2 configured -- resuming normal operations
[Sun Dec 16 09:52:32.720930 2018] [core:notice] [pid 10313:tid 140256727914368] AH00094: Command line: '/usr/sbin/apache2'
[Sun Dec 16 09:53:50.049998 2018] [authz_core:error] [pid 10925:tid 140256630511360] [client 127.0.0.1:54568] AH01630: client denied by server configuration: /home/florian/django/myproject/myproject/myproject/wsgi.py
(myprojectenv) florian@desktop:~/django/myproject/myproject$ 
Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message проверьте правильность установки ServerName. Опять же, каково содержание ваших ALLOWED_HOSTS?
Ken4scholars 16.12.2018 10:25

В настройках Django ALLOWED_HOSTS = []

Florian C 16.12.2018 13:04

Я уже обнаружил и исправил ошибку в моей конфигурации Apache: путь к WSGI был неверным: <Directory / home / florian / django / myproject / myproject / myproject> <Files wsgi.py> Требовать все предоставлено </Files> </ Directory >

Florian C 16.12.2018 13:32

После того как я исправил путь к WSGI, ошибка изменилась: florian @ desktop: ~ $ tail -n 5 /var/log/apache2/error.log #citeste log erori [wsgi: error] [pid 3960: tid 140035682776832] [ удаленный 127.0.0.1:40593] Файл "/home/florian/django/myproject/myproject/myproject/wsgi.py", строка 12, в <module> [wsgi: error] [pid 3960: tid 140035682776832] [удаленный 127.0.0.1:40593] из django.core.wsgi import get_wsgi_application [wsgi: error] [pid 3960: tid 140035682776832] [remote 127.0.0.1:40593] ImportError: нет модуля с именем 'django' florian @ desktop: ~ $

Florian C 16.12.2018 13:36

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

Ken4scholars 16.12.2018 13:44

Вы также должны добавить WSGIPythonHome и WSGIPythonPath, чтобы правильно указывать на ваш файл virtualenv. Проверьте эту страницу в документации docs.djangoproject.com/en/dev/howto/deployment/wsgi/modwsgi

Ken4scholars 16.12.2018 13:49
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
1
6
246
1

Ответы 1

Вы не указали имя сервера в конфигурации apache:

ServerName localhost

Также убедитесь, что вы указали allowed_host в своем settings.py.

ALLOWED_HOSTS = ["*"]

Другие вопросы по теме