Nginx plugin for Certbot that enables automated SSL/TLS certificate management and deployment for Nginx web servers.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
The NginxConfigurator class is the primary plugin interface for Certbot, providing automated SSL/TLS certificate management and deployment for Nginx web servers. It handles certificate installation, virtual host management, nginx server control, and configuration enhancements.
Initialize and prepare the nginx configurator for certificate operations.
class NginxConfigurator:
"""Nginx configurator for Certbot.
Args:
config: Configuration object
name: Plugin name
Attributes:
description: str = "Nginx Web Server plugin"
DEFAULT_LISTEN_PORT: str = '80'
SSL_DIRECTIVES: list[str] = ['ssl_certificate', 'ssl_certificate_key', 'ssl_dhparam']
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Initialize nginx configurator with optional version parameters."""
def prepare(self) -> None:
"""Prepare the authenticator/installer.
Verifies nginx installation, validates configuration, initializes parser,
and sets up SSL options.
Raises:
errors.NoInstallationError: If nginx binary cannot be found
errors.MisconfigurationError: If nginx configuration is invalid
"""
@classmethod
def add_parser_arguments(cls, add: Callable[..., None]) -> None:
"""Add command-line arguments for nginx plugin.
Args:
add: Function to add arguments to parser
"""
def install_ssl_options_conf(self, options_ssl: str, options_ssl_digest: str) -> None:
"""Copy SSL options file into system config directory if required.
Args:
options_ssl: Path to SSL options file
options_ssl_digest: Path to SSL options digest file
"""Deploy SSL/TLS certificates to nginx virtual hosts with automatic configuration.
def deploy_cert(self, domain: str, cert_path: str, key_path: str,
chain_path: str, fullchain_path: str) -> None:
"""Deploy certificate to specified virtual host.
Args:
domain: Domain name to deploy certificate for
cert_path: Path to certificate file
key_path: Path to private key file
chain_path: Path to certificate chain file
fullchain_path: Path to full certificate chain file
Raises:
errors.PluginError: When unable to deploy certificate
"""Select and manage nginx virtual hosts for certificate operations.
def choose_vhosts(self, target_name: str, create_if_no_match: bool = False) -> list[VirtualHost]:
"""Choose virtual hosts based on domain name.
Makes vhost SSL-enabled if not already. Follows nginx server block
selection rules preferring blocks that are already SSL.
Args:
target_name: Domain name to match
create_if_no_match: Create new vhost from default if no match found
Returns:
List of SSL vhosts associated with name
Raises:
errors.MisconfigurationError: Cannot find matching VirtualHost
"""
def choose_redirect_vhosts(self, target_name: str, port: str) -> list[VirtualHost]:
"""Choose virtual hosts for redirect enhancement.
Args:
target_name: Domain name
port: Port number
Returns:
List of vhosts associated with name
"""
def get_all_names(self) -> set[str]:
"""Get all names found in nginx configuration.
Returns:
Set of all server names, aliases, and reverse DNS entries
"""
def ipv6_info(self, host: str, port: str) -> tuple[bool, bool]:
"""Get IPv6 configuration information.
Args:
host: Host to check ipv6only directive for
port: Port to check ipv6only directive for
Returns:
Tuple of (ipv6_active, ipv6only_present) where ipv6_active indicates
if any server block listens on IPv6 and ipv6only_present indicates
if ipv6only=on exists for the specified port
"""
def choose_redirect_vhosts(self, target_name: str, port: str) -> list[VirtualHost]:
"""Choose virtual hosts for redirect enhancement.
Chooses vhost most closely matching target_name that is listening
on port without using SSL.
Args:
target_name: Domain name
port: Port number
Returns:
List of vhosts associated with name
"""
def choose_auth_vhosts(self, target_name: str) -> tuple[list[VirtualHost], list[VirtualHost]]:
"""Choose virtual hosts for authentication challenges.
Returns HTTP and HTTPS vhosts with server_name matching target_name.
If no HTTP vhost exists, attempts to clone from default vhost.
Args:
target_name: Non-wildcard domain name
Returns:
Tuple of (HTTP vhosts, HTTPS vhosts)
"""Apply security and functionality enhancements to nginx configuration.
def enhance(self, domain: str, enhancement: str,
options: Optional[Union[str, list[str]]] = None) -> None:
"""Enhance configuration with security features.
Args:
domain: Domain to enhance
enhancement: Enhancement type ('redirect', 'ensure-http-header', 'staple-ocsp')
options: Enhancement-specific options
Raises:
errors.PluginError: Unsupported enhancement
"""
def supported_enhancements(self) -> list[str]:
"""Get currently supported enhancements.
Returns:
List of supported enhancement names
"""Perform and clean up ACME HTTP-01 challenges for domain validation.
def perform(self, achalls: list[KeyAuthorizationAnnotatedChallenge]) -> list[KeyAuthorizationChallengeResponse]:
"""Perform configuration-related challenges.
Args:
achalls: List of annotated challenges
Returns:
List of challenge responses
"""
def cleanup(self, achalls: list[KeyAuthorizationAnnotatedChallenge]) -> None:
"""Revert all challenges.
Args:
achalls: List of annotated challenges to clean up
"""
def get_chall_pref(self, unused_domain: str) -> list[type[Challenge]]:
"""Return list of challenge preferences.
Returns:
List containing HTTP01 challenge type
"""
def auth_hint(self, failed_achalls: Iterable[KeyAuthorizationAnnotatedChallenge]) -> str:
"""Provide authentication failure hint.
Args:
failed_achalls: Failed annotated challenges
Returns:
Human-readable hint message for authentication failures
"""Control nginx server operations including restart and configuration testing.
def restart(self) -> None:
"""Restart nginx server.
Raises:
errors.MisconfigurationError: If reload fails
"""
def config_test(self) -> None:
"""Check nginx configuration for errors.
Raises:
errors.MisconfigurationError: If config test fails
"""
def get_version(self) -> tuple[int, ...]:
"""Get version of nginx server.
Returns:
Version tuple (e.g., (1, 18, 0))
Raises:
errors.PluginError: Unable to find nginx version or unsupported
"""
def more_info(self) -> str:
"""Get human-readable string about the module.
Returns:
Module information string
"""Save and manage configuration changes with checkpoint support.
def save(self, title: Optional[str] = None, temporary: bool = False) -> None:
"""Save all changes to configuration files.
Args:
title: Save title for checkpoint
temporary: Whether changes will be quickly reversed
Raises:
errors.PluginError: Error saving configuration or creating checkpoint
"""
def recovery_routine(self) -> None:
"""Revert all previously modified files.
Raises:
errors.PluginError: Unable to recover configuration
"""
def revert_challenge_config(self) -> None:
"""Clean up challenge configurations.
Raises:
errors.PluginError: Unable to revert challenge config
"""
def rollback_checkpoints(self, rollback: int = 1) -> None:
"""Rollback saved checkpoints.
Args:
rollback: Number of checkpoints to revert
Raises:
errors.PluginError: Problem with input or unable to revert
"""@property
def nginx_conf(self) -> str:
"""Path to nginx.conf file."""
@property
def mod_ssl_conf(self) -> str:
"""Path to SSL configuration file."""
@property
def mod_ssl_conf_src(self) -> str:
"""Path to SSL configuration template source."""from certbot_nginx._internal.configurator import NginxConfigurator
from certbot.configuration import NamespaceConfig
# Initialize configurator
config = NamespaceConfig()
configurator = NginxConfigurator(config, name='nginx')
# Prepare for operations
configurator.prepare()
# Deploy certificate
configurator.deploy_cert(
domain='example.com',
cert_path='/etc/letsencrypt/live/example.com/cert.pem',
key_path='/etc/letsencrypt/live/example.com/privkey.pem',
chain_path='/etc/letsencrypt/live/example.com/chain.pem',
fullchain_path='/etc/letsencrypt/live/example.com/fullchain.pem'
)
# Apply redirect enhancement
configurator.enhance('example.com', 'redirect')
# Save changes
configurator.save("Certificate installation and redirect")# Get all virtual hosts matching domain
vhosts = configurator.choose_vhosts('example.com', create_if_no_match=True)
# Get all configured domain names
all_names = configurator.get_all_names()
print(f"Configured domains: {all_names}")Install with Tessl CLI
npx tessl i tessl/pypi-certbot-nginx