joejordan / letsencrypt-docker-compose

Set up Nginx and Let’s Encrypt with a Docker Compose project that automatically obtains and renews free Let's Encrypt SSL/TLS certificates and sets up HTTPS in Nginx for multiple domain names. Configuration is done using a simple CLI tool. Updated in 2024 to support Docker changes.
Apache License 2.0
2 stars 0 forks source link

[BUG] Adding a sub-domain creates a certificate issue when visiting www on a non-www enabled root domain #1

Open joejordan opened 8 months ago

joejordan commented 8 months ago

Prerequisites

Docker Compose Version and Environment

Describe the Bug

When I added a subdomain, www did not automatically redirect to the non-www root url.

Expected Behavior

When www is not enabled on a domain, http and https www.domain.com should redirect to domain.com

Actual Behavior

http redirects to https but will display a certificate error because it's finding another sub-domain's certificate.

Steps to Reproduce

Please provide detailed steps for reproducing the issue.

  1. add root domain (production certificates)
  2. add a sub-domain for the same root domain (prod certs)
  3. Visit https://www.domain.com in an incognito window and get a NET::ERR_CERT_COMMON_NAME_INVALID from the browser. Investigating the certificate shows it's a cert for the sub-domain.

Additional Context

N/A

Logs

N/A

joejordan commented 8 months ago

Here's a manual solution that I found works. Edit the domain.com.conf and add the following to the top of the config. This will explicitly redirect www traffic to non-www.

# www redirect directive
server {
    listen 80;
    listen [::]:80;
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.domain.com;

    # Serve ACME challenge files from a specific location
    location /.well-known/acme-challenge/ {
        root /var/www/certbot/domain.com;
    }

    # Redirect all other requests to the non-www domain
    location / {
        return 301 https://domain.com$request_uri;
    }
}