Apache-2.2

如果我在 URL 中手動輸入 HTTPS://,Apache 站點會進入錯誤頁面

  • April 3, 2021

如果我輸入example.com它重定向到的 URL,https://www.example.com這很好,與輸入相同,http://example.com我會得到正確的重定向到https://www.example.com.

但是,如果我輸入https://example.com它會將我帶到警告 SSL 證書無效頁面。在檢查了證書的域後,我意識到它會將我帶到伺服器上完全不同的網站(如果我直接在 URL 中輸入我的 VPS IP 地址,就會出現同一個網站。)

這是我的配置文件:

<VirtualHost *:80>
   ServerName example.com
   Redirect permanent / https://www.example.com/
</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost *:443>

       ServerName www.example.com
       ServerAlias *.example.com
       ServerAdmin noreply@example.com
       DocumentRoot /var/www/html

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

       Alias /static /home/user/example/static
       <Directory /home/user/example/static>
               Require all granted
       </Directory>

       <Directory /home/user/example/example>
               <Files wsgi.py>
                       Require all granted
               </Files>
       </Directory>

       WSGIScriptAlias / /home/user/example/example/wsgi.py
       WSGIDaemonProcess exsite python-path=/home/user/example python-home=/home/user/example/venv
       WSGIProcessGroup exsite


RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]

SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

這些都不涵蓋example.com,而是使用預設站點:

ServerName www.example.com 
ServerAlias *.example.com

如果您的證書是萬用字元證書example.com,您可以將其添加到您的ServerAlias

ServerName www.example.com 
ServerAlias example.com *.example.com

也可以通過添加另一個VirtualHost *:443塊來完全避免使用 mod_rewrite:

<IfModule mod_ssl.c>
   <VirtualHost *:443>
       ServerName www.example.com
       #...
   </VirtualHost>

   <VirtualHost *:443>
       ServerName example.com
       ServerAlias *.example.com

       Redirect permanent / https://www.example.com/

       SSLCertificateFile /etc/letsencrypt/live/www.example.com/fullchain.pem 
       SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
       Include /etc/letsencrypt/options-ssl-apache.conf
   </VirtualHost>
</IfModule>

引用自:https://serverfault.com/questions/1059218