brett
brett

Reputation: 195

Apache2 Redirect www to https ... this is killing me trying to figure this out

Server Ubuntu 22.04

apache2 -v 2.4.52

Website alias for this question: example.com

I have configured and enabled my virtual host sites-enabled example.conf file as shown below. Default is disabled. My site has no .htaccess file. When I go example.com in the browser, site launches and SSL checks okay (padlock). When I go http://example.com, site launches and SSL checks okay (padlock). However, when I go www.example.com, site launches but SSL fails (shows site insecure, padlock red). I thought I set up the redirect properly in example.conf but I guess I am missing something. Please review my .conf file below and suggest changes to or trouble shooting method to help me get this problem sorted out.

<VirtualHost *:80 *:443>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
    DocumentRoot /var/www/html/example
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
</VirtualHost>

<VirtualHost *:80 *:443>
    ServerName www.example.com
    Redirect permanent / https://example.com/
    DocumentRoot /var/www/html/example  
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/www.example.com/cert.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/www.example.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/www.example.com/chain.pem
</VirtualHost>

Upvotes: 0

Views: 29

Answers (1)

0xn0b174
0xn0b174

Reputation: 1022

issue:

  1. incorrect ssl configuration
  2. duplicated virtual host

solution:

  1. a single certificate should cover both your domain, you can obtain it by following command
sudo certbot --apache -d example.com -d www.example.com

  1. simplify your apache configuraion
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/html/example
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    
    SSLEngine on
    SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
    
    # Ensure that www.example.com redirects to example.com
    <If "%{HTTP_HOST} == 'www.example.com'">
        Redirect permanent / https://example.com/
    </If>
</VirtualHost>

Upvotes: 0

Related Questions