How to Check Certificate Expiry and HTTPS Chain via OpenSSL
We separately verify the local certificate and what the server actually serves: validity period, hostname, and chain trust require distinct checks.

In this article
В панели сертификат выглядит свежим, а браузер всё ещё сообщает об ошибке HTTPS. Возможно, обновлённый файл не загружен веб-сервером, проверяется другой узел или не хватает промежуточного сертификата. Сначала разделите две задачи: чтение локального файла и проверку действующего соединения.
Прочитайте локальный сертификат
Примеры рассчитаны на OpenSSL 3.x. Файл certificate.pem — условное имя публичного сертификата в формате PEM, а не закрытого ключа. Подставьте путь к своему файлу, который разрешено читать.
openssl x509 -in certificate.pem -noout -subject -issuer -dates
Команда показывает владельца, издателя и даты. Это не проверка того, какой сертификат сейчас обслуживает сайт. Успешное чтение файла также не означает, что цепочка доверенная и имя сайта подходит.
Для проверки, не истекает ли срок в ближайшие семь суток:
openssl x509 -in certificate.pem -noout -checkend 604800
Число задано в секундах. Ненулевой результат этой проверки требует разобраться с сообщением и кодом завершения; в сценарии не скрывайте ошибку чтения файла под общим уведомлением об истечении срока.
Проверьте реальный сервер
Введите доменное имя без протокола и пути:
read -r TARGET_HOST
printf '' | openssl s_client -connect "${TARGET_HOST}:443" -servername "$TARGET_HOST" -verify_hostname "$TARGET_HOST" -verify_return_error -showcerts
Параметр имени сервера нужен для SNI, а отдельная проверка имени сопоставляет сертификат с ожидаемым узлом. Режим возврата ошибки не позволяет считать продолженное после ошибки проверки соединение доказательством доверия.
Утилита использует доступные ей доверенные центры сертификации. Их набор может отличаться от браузерного или корпоративного хранилища. Сохраните версию OpenSSL и точный текст ошибки. Для частного центра доверия требуется его корректная настройка, а не отключение проверки сертификатов.
Что означает список сертификатов
Выведенные сертификаты — то, что прислал сервер. Сам факт наличия списка не доказывает, что цепочка построена и проверена. Смотрите итог проверки и учитывайте имя узла, сроки и доверенное хранилище.
Если перед сайтом стоит CDN или балансировщик, вы проверяете публичный узел этой цепочки. Локальный сертификат на исходном сервере может быть другим. Это допустимо в некоторых схемах, но должно соответствовать настройке всей цепи соединений.
Разберите расхождение
Пример: локальный файл уже новый, а удалённый сервер возвращает старые даты. Проверьте, тот ли путь использует сервис, применена ли конфигурация и одинаково ли обновлены все обслуживающие узлы. Один успешный ответ балансировщика не исключает устаревший сертификат на другом узле.
Закрытый ключ не нужен для этих проверок и не должен попадать в отчёт. Зафиксируйте имя, дату окончания, издателя, результат проверки цепочки и точку подключения. После исправления повторите проверку соединения и откройте сайт обычным клиентом. Исправный локальный файл — только часть результата; пользователю важен сертификат, полученный в реальном HTTPS-сеансе.
Проверка срока зависит от корректных системных часов. При неожиданном результате сначала сопоставьте время машины с доверенным источником.
The certificate looks fresh in the control panel, yet the browser still reports an HTTPS error. The updated file may not have been uploaded to the web server, a different node might be checked, or an intermediate certificate may be missing. First, separate the two tasks: reading the local file and verifying the active connection.
Read the local certificate
Examples are calculated for OpenSSL 3.x. The file certificate.pem is a placeholder name for a public certificate in PEM format, not a private key. Substitute the path to your own file, which must be readable.
openssl x509 -in certificate.pem -noout -subject -issuer -dates
The command displays the owner, issuer, and dates. This does not verify which certificate the site currently serves. Successfully reading the file also does not guarantee that the chain is trusted or that the site name matches.
To check if the certificate expires within the next seven days:
openssl x509 -in certificate.pem -noout -checkend 604800
The number is specified in seconds. A non-zero result from this check requires investigating the message and exit code; in a script, do not hide file read errors under a generic expiry notification.
Check the actual server
Enter the domain name without protocol and path:
read -r TARGET_HOST
printf '' | openssl s_client -connect "${TARGET_HOST}:443" -servername "$TARGET_HOST" -verify_hostname "$TARGET_HOST" -verify_return_error -showcerts
The server name parameter is required for SNI, and a separate name check matches the certificate to the expected node. Error return mode prevents a connection resumed after a check error from being treated as proof of trust.
The utility uses the trusted certificate authorities available to it. This set may differ from the browser or corporate store. Save the OpenSSL version and the exact error text. For a private trust center, correct configuration is required, not disabling certificate checks.
What the certificate list means
The output certificates are what the server sent. The mere presence of a list does not prove the chain is built and verified. Review the check result and consider the node name, validity periods, and the trusted store.
If a CDN or load balancer stands in front of the site, you are checking the public node of that chain. The local certificate on the origin server may be different. This is acceptable in some schemes but must align with the configuration of the entire connection chain.
Analyze the discrepancy
Example: the local file is already new, but the remote server returns old dates. Check whether the service uses the correct path, whether the configuration has been applied, and whether all serving nodes have been updated identically. A single successful response from a load balancer does not rule out an outdated certificate on another node.
The private key is not needed for these checks and must not appear in the report. Record the name, expiration date, issuer, chain verification result, and connection endpoint. After fixing the issue, repeat the connection check and open the site with a standard client. A valid local file is only part of the result; the user cares about the certificate received during a real HTTPS session.
Validity period checks depend on correct system time. If you encounter an unexpected result, first compare the machine's time with a trusted source.

Discussion 0
Share your experience and ask questions. Comments without links appear after editorial review.
No comments yet. Start the discussion.