Apache2 默认页面不显示 http://、https:// 或 www. 前缀

Apache2 默认页面不显示 http://、https:// 或 www. 前缀

我在装有 apache2 的 ubuntu 19.04 服务器上运行 django webapp。我已使用 certbot 安装了 SSL 证书,但无法将来自 domainname.com 的流量引导至https://www.域名.com。每当我浏览 domainname.com 时,都会显示 apache 默认页面。如果我浏览 www.domainname.com,网站就会按预期显示。https://域名.com但工作正常。

我还没有找到适合我的解决方案,困扰我的是我有一个 ssl 证书和两个 conf 文件。

在运行 certbot 时,创建了一个额外的配置文件,所以我现在有了 domainname.conf 和 domainname-le-ssl.conf。现在在我的 domainname.conf 中,我添加了重写,以便所有到我的 80 端口的流量都重定向到 https::

<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.domainname.com
        ServerAdmin *******
        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


        RewriteEngine on
        RewriteCond %{SERVER_NAME} =www.domainname.com
        RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

我的 domainname-le-ssl.conf 是由 certbot 自动生成的,没有任何重写。现在我尝试了一些重写,但似乎都没有发现所有流量都应该通过 https 并传输到 www.domainname.com。我应该在这个文件中还是在我注册域名的服务中修复这个问题?

答案1

我通过将重写逻辑替换为以下内容来修复此问题:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

相关内容