Apache,mod-wsgi:项目提供任何 URL,ServerName 被忽略

Apache, mod-wsgi: Any URL is served by project, ServerName is ignored

我正在 Ubuntu 20 上设置一个 Django 项目和 Apache。下面的设置正确显示了 Django 项目,但是指向服务器 IP 地址的任何 URL 都为该项目提供服务。我显然需要将其限制在我的特定网站 mysite.com。 ServerName 被忽略。

我看过其他的 question/answers. 但是,他们通常会提到 httpd.conf,它在 Apache 中不再使用。或者,没有公认的答案。或者,它与我的设置无关。另外,我被告知不要触摸 apache2.conf。这是一个全新的安装实例,所以没有奇怪的东西。

我最终需要在同一台服务器上提供多个站点。

安装 Apache mod-wsgi:

sudo apt install apache2 apache2-utils ssl-cert libapache2-mod-wsgi
sudo a2enmod rewrite
sudo systemctl restart apache2

设置.conf文件并激活它:

Copy mysite.com.conf to /etc/apache2/sites-available

sudo a2ensite mysite.com.conf
sudo a2dissite 000-default.conf
sudo systemctl reload apache2
sudo systemctl restart apache2

mysite.com.conf:

<VirtualHost *:80>

    WSGIApplicationGroup %{GLOBAL}
    WSGIDaemonProcess test_project_ns processes=1 threads=10 python-path=/home/ubuntu/test_project python-home=/home/ubuntu/test_project/test_env
    WSGIProcessGroup test_project_ns

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ServerName mysite.com
    ServerAlias www.mysite.com

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    
    <Directory /home/ubuntu/test_project/test_ui>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>
   
    WSGIScriptAlias / /home/ubuntu/test_project/test_ui/wsgi.py

</VirtualHost>

结果:

mysite.com 正确地服务于 Django 项目,但任何其他指向服务器的网站也是如此。

apache2ctl -S 的输出:

VirtualHost configuration:
*:80                   mysite.com (/etc/apache2/sites-enabled/mysite.com.conf:1)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex watchdog-callback: using_defaults
Mutex rewrite-map: using_defaults
Mutex default: dir="/var/run/apache2/" mechanism=default
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33 not_used
Group: name="www-data" id=33 not_used

因此,如果 apache 找不到 URL 的匹配项,它会使用第一个虚拟主机,而不考虑 ServerName。因此,我在真实主机之前添加了一个阻塞虚拟主机。现在,所有不匹配 ServerName 或 ServerAlias 的站点都会显示一条标准的禁止消息。

这也适用于多个 site.com.conf 文件。我将阻塞虚拟主机添加到每个文件的顶部,因此当有多个文件时,我不必担心哪个虚拟主机是“第一个”。

<VirtualHost *:80>
     <Location />
        Deny from all
    </Location>
</VirtualHost>
<VirtualHost *:80>

    ServerName mysite.com
    .....
        
</VirtualHost>