nginx-proxy-manager/backend/lib/nginx-errors.js
Tom Winnerl 798596ec79 fix(review): allow variable forward paths on regex and named locations
Problem: preflightLocation() quarantined every regex (`~`, `~*`) or named
(`@x`) location that had a forward path, so a working setup such as
`location ~ ^/api/(.*)$` with forward path `/v1/$1`, or `@fallback` with
`/fb$request_uri`, answered 503 after the upgrade. nginx only rejects a URI
in the proxy_pass of such a location when the proxy_pass has no variable
("cannot have URI part in location given by regular expression"); with a
variable it is compiled as a script and has always worked.

Fix: the check only quarantines a forward path without a `$`. A forward
path with a variable is rendered literally, exactly as before, through the
previous fix (static mode, no rewrite; no nested asset location when it uses
a capture, because the nested regex would replace $1). The messages and the
nginx error hint now say "without an nginx variable" and suggest a capture.

Tests: unit tests for the preflight (literal path still quarantined, `$1`,
named captures, `$request_uri`, named locations allowed) and the rendering.
The nginx-semantics generator now applies preflightLocation() like the
backend does, and new cases (`~ ^/rx/(.*)$` -> `/v1/$1`, `~*` with a named
capture, a cached regex location, `@fb` reached through error_page) must
answer like the old literal rendering: 9 diffs before, DIFFS=0 now.

Cypress (ProxyHostLocations): `~ ^/cap/(.*)$` with forward path `/$1` is
saved ok and `/cap/dashboard` serves examplesite's /dashboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 09:03:56 +01:00

288 lines
9.7 KiB
JavaScript

/**
* Helpers to turn `nginx -t` output into something a user can act on.
*
* This module is intentionally free of database / model imports so it can be
* unit tested with `node --test`.
*/
const MANAGED_FILE_REGEX = /^\/data\/nginx\/(proxy_host|redirection_host|dead_host|stream)\/(\d+)\.conf$/;
/**
* Removes noise from nginx stderr output:
* - the docker-ism startup alert "could not open error log file: open() "/var/log/nginx/error.log"" which is
* always a false positive (real failures that mention that path, e.g. an [emerg] for a host's own
* error_log, are kept so the broken host can still be identified)
* - the warning that the "user" directive is ignored, which nginx always prints when it runs as PUID
* - the trailing "configuration file ... test failed" line
*
* @param {String} output
* @returns {String}
*/
const cleanNginxOutput = (output) => {
return `${output || ""}`
.split("\n")
.filter((line) => !/\[alert\].*could not open error log file: open\(\) "\/var\/log\/nginx\/error\.log"/.test(line))
.filter((line) => !/\[warn\] the "user" directive makes sense only if the master process runs with super-user privileges/.test(line))
.filter((line) => !/configuration file .* test failed/.test(line))
.filter((line) => line.trim() !== "")
.join("\n")
.trim();
};
/**
* Finds the first real error in the `nginx -t` output.
*
* @param {String} output raw stderr of `nginx -t`
* @returns {{file: String|null, line: Number|null, message: String, output: String}}
*/
const parseNginxTestOutput = (output) => {
const cleaned = cleanNginxOutput(output);
const lines = cleaned.split("\n");
const errorLine =
lines.find((line) => /\[(emerg|alert|crit|error)\]/.test(line)) ||
lines.find((line) => line.trim() !== "" && !/syntax is ok/.test(line)) ||
"";
// "nginx: [emerg] msg" or "2026/11/04 10:00:00 [emerg] 12#12: msg"
let message = errorLine
.replace(/^.*?\[(emerg|alert|crit|error|warn)\]\s*(\d+#\d+:\s*)?/, "")
.replace(/^nginx:\s*/, "");
let file = null;
let line = null;
const match = message.match(/\s+in (\S+):(\d+)\s*$/);
if (match) {
file = match[1];
line = Number.parseInt(match[2], 10);
message = message.slice(0, match.index);
}
return {
file,
line,
message: message.trim(),
output: cleaned,
};
};
/**
* @param {String} file
* @returns {{host_type: String, host_id: Number}|null}
*/
const parseManagedFile = (file) => {
const match = `${file || ""}`.match(MANAGED_FILE_REGEX);
if (!match) {
return null;
}
return {
host_type: match[1],
host_id: Number.parseInt(match[2], 10),
};
};
const stripPort = (upstream) => {
// [::1]:80 -> [::1], host:80 -> host
if (upstream.startsWith("[")) {
const end = upstream.indexOf("]");
return end > -1 ? upstream.slice(0, end + 1) : upstream;
}
const parts = upstream.split(":");
return parts.length === 2 ? parts[0] : upstream;
};
/**
* Each rule turns a raw nginx message into a short sentence (without a trailing full stop)
* plus an optional hint. `code` names the rule, the UI words the hint from it (nginx-error.hint.<code>).
*/
const RULES = [
{
code: "host_not_found",
regex: /host not found in upstream "([^"]+)"/,
text: (m) => `host "${stripPort(m[1])}" could not be resolved`,
hint: "Check that the host name is spelled correctly, that the container or server is running, and that NPM can reach it on a shared network.",
},
{
code: "no_resolver",
regex: /no resolver defined to resolve (\S+)/,
text: (m) => `no DNS resolver is configured to resolve "${m[1]}"`,
hint: "The nginx resolver is disabled (DISABLE_RESOLVER). Use an IP address or enable the resolver.",
},
{
code: "invalid_port",
regex: /invalid port in upstream "([^"]+)"/,
text: (m) => `invalid port in upstream "${m[1]}"`,
hint: 'The port must be a number between 1 and 65535. A forward path must start with "/".',
},
{
code: "invalid_url",
regex: /invalid URL prefix in "([^"]+)"/,
text: (m) => `invalid URL "${m[1]}"`,
hint: "Check the scheme and host of the upstream.",
},
{
code: "unknown_directive",
regex: /unknown directive "([^"]+)"/,
text: (m) => `unknown directive "${m[1]}"`,
hint: "Check the spelling of the directive. If it comes from an nginx module, that module may not be available.",
},
{
code: "unknown_variable",
regex: /unknown "([^"]+)" variable/,
text: (m) => `unknown variable "$${m[1]}"`,
hint: "Check the spelling of the variable, or define it with set or map.",
},
{
code: "invalid_arguments",
regex: /invalid number of arguments in "([^"]+)" directive/,
text: (m) => `wrong number of arguments for "${m[1]}"`,
hint: "Check for a missing or extra value, or a missing semicolon at the end of the previous line.",
},
{
code: "duplicate_directive",
regex: /"([^"]+)" directive is duplicate/,
text: (m) => `"${m[1]}" is set more than once`,
hint: "Remove the duplicate. NPM may already set this directive for you.",
},
{
code: "duplicate_location",
regex: /duplicate location "([^"]+)"/,
text: (m) => `the location "${m[1]}" is defined more than once`,
hint: "Each location path may only be used once per host, including locations in the advanced configuration.",
},
{
code: "unexpected_close_brace",
regex: /unexpected "\}"/,
text: () => 'unexpected "}"',
hint: "Check that every { has a matching }.",
},
{
code: "unexpected_open_brace",
regex: /unexpected "\{"/,
text: () => 'unexpected "{"',
hint: "Check that every { has a matching } and that the previous line ends with a semicolon.",
},
{
code: "unexpected_semicolon",
regex: /unexpected ";"/,
text: () => 'unexpected ";"',
hint: "Check for a stray semicolon.",
},
{
code: "unexpected_eof",
regex: /unexpected end of file, expecting "([^"]+)"/,
text: (m) => `the configuration ends unexpectedly, a "${m[1]}" is missing`,
hint: "Check for a missing semicolon or closing }.",
},
{
code: "regex_uri_part",
regex: /"proxy_pass" cannot have URI part in location given by regular expression/,
text: () => "a forward path without an nginx variable can't be used with a regular-expression or named location",
hint: "Use a capture or variable in the forward path (/v1/$1), remove the forward path or use a prefix location.",
},
{
code: "invalid_regex",
regex: /pcre2?_compile\(\) failed: (.+?)(?: in "[^"]*")?(?: at "[^"]*")?$/,
text: (m) => `invalid regular expression (${m[1].trim()})`,
hint: "Check the regular expression syntax of the location path or rewrite.",
},
{
code: "certificate_load",
regex: /cannot load certificate(?: key)? "([^"]+)"/,
text: (m) => `the certificate file "${m[1]}" could not be loaded`,
hint: "The certificate may have been deleted or not issued yet. Select another certificate or renew it.",
},
{
code: "certificate_load",
regex: /BIO_new_file\(\) failed/,
text: () => "a certificate file could not be loaded",
hint: "The certificate may have been deleted or not issued yet. Select another certificate or renew it.",
},
{
code: "no_certificate",
regex: /no "ssl_certificate" is defined/,
text: () => "SSL is enabled but no certificate is defined",
hint: "Select a certificate for this host.",
},
{
code: "invalid_parameter",
regex: /invalid parameter "([^"]+)"/,
text: (m) => `invalid parameter "${m[1]}"`,
hint: null,
},
{
code: "location_nesting",
regex: /location "([^"]+)" cannot be inside the (exact|named) location "([^"]+)"/,
text: (m) => `the location "${m[1]}" can't be placed inside the ${m[2]} location "${m[3]}"`,
hint: "Exact (=) and named (@) locations can't contain other locations.",
},
{
code: "location_not_allowed",
regex: /"location" directive is not allowed here/,
text: () => 'a "location" block is not allowed here',
hint: "Locations can only be placed in a server block or inside another location.",
},
{
code: "directive_not_allowed",
regex: /"([^"]+)" directive is not allowed here/,
text: (m) => `the "${m[1]}" directive is not allowed here`,
hint: "This directive can't be used in this context.",
},
{
code: "server_names_hash",
regex: /could not build server_names_hash|could not build map_hash/,
text: () => "too many or too long domain names",
hint: null,
},
{
code: "address_in_use",
regex: /bind\(\) to (\S+) failed/,
text: (m) => `the address ${m[1]} is already in use`,
hint: "Another host or service already listens on this port.",
},
];
/**
* @param {String} message nginx message without the "nginx: [emerg]" prefix and without the "in file:line" suffix
* @returns {{text: String, hint: String|null, code: String|null}} code: the rule that matched
*/
const humaniseNginxMessage = (message) => {
const msg = `${message || ""}`.trim();
for (const rule of RULES) {
const match = msg.match(rule.regex);
if (match) {
return { text: rule.text(match), hint: rule.hint, code: rule.code };
}
}
return { text: msg || "nginx rejected the configuration", hint: null, code: null };
};
const capitalise = (str) => (str ? str.charAt(0).toUpperCase() + str.slice(1) : str);
const sentence = (str) => {
const s = `${str || ""}`.trim();
return /[.!?]$/.test(s) ? s : `${s}.`;
};
/**
* @param {Object} meta host meta written by configure
* @returns {boolean} true when the host is offline because an upstream name did not resolve, or a custom
* location is unresolved. Both can fix themselves once the upstream container is up.
*/
const mayResolveLater = (meta) => {
if (meta?.nginx_online === false) {
const text = `${meta.nginx_details?.nginx_output || ""} ${meta.nginx_err || ""}`;
return /host not found in upstream/i.test(text);
}
return Array.isArray(meta?.nginx_locations) && meta.nginx_locations.some((loc) => loc?.status === "unresolved");
};
export {
capitalise,
cleanNginxOutput,
humaniseNginxMessage,
MANAGED_FILE_REGEX,
mayResolveLater,
parseManagedFile,
parseNginxTestOutput,
sentence,
};