0
# Main Configurator
1
2
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.
3
4
## Capabilities
5
6
### Plugin Initialization and Setup
7
8
Initialize and prepare the nginx configurator for certificate operations.
9
10
```python { .api }
11
class NginxConfigurator:
12
"""Nginx configurator for Certbot.
13
14
Args:
15
config: Configuration object
16
name: Plugin name
17
18
Attributes:
19
description: str = "Nginx Web Server plugin"
20
DEFAULT_LISTEN_PORT: str = '80'
21
SSL_DIRECTIVES: list[str] = ['ssl_certificate', 'ssl_certificate_key', 'ssl_dhparam']
22
"""
23
24
def __init__(self, *args: Any, **kwargs: Any) -> None:
25
"""Initialize nginx configurator with optional version parameters."""
26
27
def prepare(self) -> None:
28
"""Prepare the authenticator/installer.
29
30
Verifies nginx installation, validates configuration, initializes parser,
31
and sets up SSL options.
32
33
Raises:
34
errors.NoInstallationError: If nginx binary cannot be found
35
errors.MisconfigurationError: If nginx configuration is invalid
36
"""
37
38
@classmethod
39
def add_parser_arguments(cls, add: Callable[..., None]) -> None:
40
"""Add command-line arguments for nginx plugin.
41
42
Args:
43
add: Function to add arguments to parser
44
"""
45
46
def install_ssl_options_conf(self, options_ssl: str, options_ssl_digest: str) -> None:
47
"""Copy SSL options file into system config directory if required.
48
49
Args:
50
options_ssl: Path to SSL options file
51
options_ssl_digest: Path to SSL options digest file
52
"""
53
```
54
55
### Certificate Deployment
56
57
Deploy SSL/TLS certificates to nginx virtual hosts with automatic configuration.
58
59
```python { .api }
60
def deploy_cert(self, domain: str, cert_path: str, key_path: str,
61
chain_path: str, fullchain_path: str) -> None:
62
"""Deploy certificate to specified virtual host.
63
64
Args:
65
domain: Domain name to deploy certificate for
66
cert_path: Path to certificate file
67
key_path: Path to private key file
68
chain_path: Path to certificate chain file
69
fullchain_path: Path to full certificate chain file
70
71
Raises:
72
errors.PluginError: When unable to deploy certificate
73
"""
74
```
75
76
### Virtual Host Management
77
78
Select and manage nginx virtual hosts for certificate operations.
79
80
```python { .api }
81
def choose_vhosts(self, target_name: str, create_if_no_match: bool = False) -> list[VirtualHost]:
82
"""Choose virtual hosts based on domain name.
83
84
Makes vhost SSL-enabled if not already. Follows nginx server block
85
selection rules preferring blocks that are already SSL.
86
87
Args:
88
target_name: Domain name to match
89
create_if_no_match: Create new vhost from default if no match found
90
91
Returns:
92
List of SSL vhosts associated with name
93
94
Raises:
95
errors.MisconfigurationError: Cannot find matching VirtualHost
96
"""
97
98
def choose_redirect_vhosts(self, target_name: str, port: str) -> list[VirtualHost]:
99
"""Choose virtual hosts for redirect enhancement.
100
101
Args:
102
target_name: Domain name
103
port: Port number
104
105
Returns:
106
List of vhosts associated with name
107
"""
108
109
def get_all_names(self) -> set[str]:
110
"""Get all names found in nginx configuration.
111
112
Returns:
113
Set of all server names, aliases, and reverse DNS entries
114
"""
115
116
def ipv6_info(self, host: str, port: str) -> tuple[bool, bool]:
117
"""Get IPv6 configuration information.
118
119
Args:
120
host: Host to check ipv6only directive for
121
port: Port to check ipv6only directive for
122
123
Returns:
124
Tuple of (ipv6_active, ipv6only_present) where ipv6_active indicates
125
if any server block listens on IPv6 and ipv6only_present indicates
126
if ipv6only=on exists for the specified port
127
"""
128
129
def choose_redirect_vhosts(self, target_name: str, port: str) -> list[VirtualHost]:
130
"""Choose virtual hosts for redirect enhancement.
131
132
Chooses vhost most closely matching target_name that is listening
133
on port without using SSL.
134
135
Args:
136
target_name: Domain name
137
port: Port number
138
139
Returns:
140
List of vhosts associated with name
141
"""
142
143
def choose_auth_vhosts(self, target_name: str) -> tuple[list[VirtualHost], list[VirtualHost]]:
144
"""Choose virtual hosts for authentication challenges.
145
146
Returns HTTP and HTTPS vhosts with server_name matching target_name.
147
If no HTTP vhost exists, attempts to clone from default vhost.
148
149
Args:
150
target_name: Non-wildcard domain name
151
152
Returns:
153
Tuple of (HTTP vhosts, HTTPS vhosts)
154
"""
155
```
156
157
### Configuration Enhancements
158
159
Apply security and functionality enhancements to nginx configuration.
160
161
```python { .api }
162
def enhance(self, domain: str, enhancement: str,
163
options: Optional[Union[str, list[str]]] = None) -> None:
164
"""Enhance configuration with security features.
165
166
Args:
167
domain: Domain to enhance
168
enhancement: Enhancement type ('redirect', 'ensure-http-header', 'staple-ocsp')
169
options: Enhancement-specific options
170
171
Raises:
172
errors.PluginError: Unsupported enhancement
173
"""
174
175
def supported_enhancements(self) -> list[str]:
176
"""Get currently supported enhancements.
177
178
Returns:
179
List of supported enhancement names
180
"""
181
```
182
183
### Challenge Handling
184
185
Perform and clean up ACME HTTP-01 challenges for domain validation.
186
187
```python { .api }
188
def perform(self, achalls: list[KeyAuthorizationAnnotatedChallenge]) -> list[KeyAuthorizationChallengeResponse]:
189
"""Perform configuration-related challenges.
190
191
Args:
192
achalls: List of annotated challenges
193
194
Returns:
195
List of challenge responses
196
"""
197
198
def cleanup(self, achalls: list[KeyAuthorizationAnnotatedChallenge]) -> None:
199
"""Revert all challenges.
200
201
Args:
202
achalls: List of annotated challenges to clean up
203
"""
204
205
def get_chall_pref(self, unused_domain: str) -> list[type[Challenge]]:
206
"""Return list of challenge preferences.
207
208
Returns:
209
List containing HTTP01 challenge type
210
"""
211
212
def auth_hint(self, failed_achalls: Iterable[KeyAuthorizationAnnotatedChallenge]) -> str:
213
"""Provide authentication failure hint.
214
215
Args:
216
failed_achalls: Failed annotated challenges
217
218
Returns:
219
Human-readable hint message for authentication failures
220
"""
221
```
222
223
### Server Management
224
225
Control nginx server operations including restart and configuration testing.
226
227
```python { .api }
228
def restart(self) -> None:
229
"""Restart nginx server.
230
231
Raises:
232
errors.MisconfigurationError: If reload fails
233
"""
234
235
def config_test(self) -> None:
236
"""Check nginx configuration for errors.
237
238
Raises:
239
errors.MisconfigurationError: If config test fails
240
"""
241
242
def get_version(self) -> tuple[int, ...]:
243
"""Get version of nginx server.
244
245
Returns:
246
Version tuple (e.g., (1, 18, 0))
247
248
Raises:
249
errors.PluginError: Unable to find nginx version or unsupported
250
"""
251
252
def more_info(self) -> str:
253
"""Get human-readable string about the module.
254
255
Returns:
256
Module information string
257
"""
258
```
259
260
### Configuration Persistence
261
262
Save and manage configuration changes with checkpoint support.
263
264
```python { .api }
265
def save(self, title: Optional[str] = None, temporary: bool = False) -> None:
266
"""Save all changes to configuration files.
267
268
Args:
269
title: Save title for checkpoint
270
temporary: Whether changes will be quickly reversed
271
272
Raises:
273
errors.PluginError: Error saving configuration or creating checkpoint
274
"""
275
276
def recovery_routine(self) -> None:
277
"""Revert all previously modified files.
278
279
Raises:
280
errors.PluginError: Unable to recover configuration
281
"""
282
283
def revert_challenge_config(self) -> None:
284
"""Clean up challenge configurations.
285
286
Raises:
287
errors.PluginError: Unable to revert challenge config
288
"""
289
290
def rollback_checkpoints(self, rollback: int = 1) -> None:
291
"""Rollback saved checkpoints.
292
293
Args:
294
rollback: Number of checkpoints to revert
295
296
Raises:
297
errors.PluginError: Problem with input or unable to revert
298
"""
299
```
300
301
### Properties
302
303
```python { .api }
304
@property
305
def nginx_conf(self) -> str:
306
"""Path to nginx.conf file."""
307
308
@property
309
def mod_ssl_conf(self) -> str:
310
"""Path to SSL configuration file."""
311
312
@property
313
def mod_ssl_conf_src(self) -> str:
314
"""Path to SSL configuration template source."""
315
```
316
317
## Usage Examples
318
319
### Basic Certificate Deployment
320
321
```python
322
from certbot_nginx._internal.configurator import NginxConfigurator
323
from certbot.configuration import NamespaceConfig
324
325
# Initialize configurator
326
config = NamespaceConfig()
327
configurator = NginxConfigurator(config, name='nginx')
328
329
# Prepare for operations
330
configurator.prepare()
331
332
# Deploy certificate
333
configurator.deploy_cert(
334
domain='example.com',
335
cert_path='/etc/letsencrypt/live/example.com/cert.pem',
336
key_path='/etc/letsencrypt/live/example.com/privkey.pem',
337
chain_path='/etc/letsencrypt/live/example.com/chain.pem',
338
fullchain_path='/etc/letsencrypt/live/example.com/fullchain.pem'
339
)
340
341
# Apply redirect enhancement
342
configurator.enhance('example.com', 'redirect')
343
344
# Save changes
345
configurator.save("Certificate installation and redirect")
346
```
347
348
### Virtual Host Selection
349
350
```python
351
# Get all virtual hosts matching domain
352
vhosts = configurator.choose_vhosts('example.com', create_if_no_match=True)
353
354
# Get all configured domain names
355
all_names = configurator.get_all_names()
356
print(f"Configured domains: {all_names}")
357
```