Technology Encyclopedia Home >HTTP request returns an error message "x509: cannot validate certificate". How to solve this problem?

HTTP request returns an error message "x509: cannot validate certificate". How to solve this problem?

The error message "x509: cannot validate certificate" typically occurs when an HTTP client (e.g., a Go program or a browser) tries to establish a secure HTTPS connection but fails to verify the server's SSL/TLS certificate. This can happen due to several reasons:

  1. Self-signed certificate: The server uses a certificate that is not signed by a trusted Certificate Authority (CA).
    Solution: Add the self-signed certificate to the client's trusted certificate store or disable certificate verification (not recommended for production).
    Example: In Go, you can use InsecureSkipVerify: true in the tls.Config, but this is insecure and should only be used for testing.

    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    
  2. Expired certificate: The server's certificate has expired.
    Solution: Renew the certificate on the server.

  3. Incorrect hostname: The certificate is valid but does not match the server's hostname.
    Solution: Ensure the server's certificate includes the correct Common Name (CN) or Subject Alternative Names (SANs) that match the hostname you're connecting to.

  4. Missing intermediate certificates: The server does not provide intermediate certificates, causing the chain of trust to break.
    Solution: Configure the server to include all intermediate certificates in the TLS handshake.

  5. Outdated CA bundle on the client: The client's trusted CA store is outdated and does not recognize the certificate issuer.
    Solution: Update the client's CA bundle (e.g., ca-certificates package on Linux).

For cloud-based applications, if you're using a managed service like Tencent Cloud's Load Balancer or Tencent Cloud's SSL Certificate Service, ensure the certificate is correctly configured and valid. Tencent Cloud's SSL Certificate Service provides free and paid certificates, and the Load Balancer can automatically manage certificate deployment.

If you're testing locally and need to bypass certificate validation (not recommended for production), you can use tools like mkcert to generate a trusted local CA and issue certificates for your development environment.

For production environments, always use certificates issued by trusted CAs and ensure proper certificate management.