Back to blog
November 17, 2026Sergei Solod11 min read

Nginx High CPU on a Static Next.js Site: Fixing Regex Redirects

A static Next.js site was burning CPU on nginx regex redirect maps. Learn how exact-key lookups, real HTTP parity tests and controlled benchmarks preserved old page and media URLs while sharply reducing CPU work.

NginxPerformancePCRERedirectsNext.js

The frontend was already compiled into static HTML. Nginx served the generated pages and media files directly, yet its workers were spending an unexpectedly large amount of CPU time on ordinary requests. There was no per-request Next.js rendering to optimize. The expensive operation happened earlier: nginx was deciding whether each URL belonged to a growing collection of historical redirects.

The eventual fix kept the old links working. Page redirects, numbered image aliases, and video aliases were retained, but thousands of regular-expression comparisons were replaced by a small number of structural matches and hash-table lookups. That change was deployed and tested against the original routing behavior. A controlled, repeated benchmark showed more than a hundredfold reduction in nginx worker CPU time for the tested request mix, without changing its HTTP responses.

Why a static Next.js export was still CPU-bound

Static export moves page rendering out of the request path; it does not remove nginx routing logic. Before nginx can serve an HTML page or image, it may normalize a path, evaluate redirect maps, select a location, check whether files exist, and construct a response. A fast filesystem cannot compensate for expensive URL matching repeated for every request.

The configuration had accumulated two different kinds of historical rules. Exact old-page aliases pointed to new canonical paths. Pagination aliases also redirected retired paths, but followed common structural patterns. Separately, renamed media paths used expressions that captured optional image numbers, and video names had their own alias rules. The problem was not that redirects existed; it was that large groups of structurally similar redirects had been encoded as individual regexes.

First rule out the CPU symptoms that look similar

The site ran on virtualized Linux, making hypervisor CPU steal an initial possibility. I compared CPU utilization, steal time, process-level consumption, memory pressure and disk wait rather than interpreting a high load average as a diagnosis. The basic tools were:

mpstat -P ALL 1 5
pidstat -u -C nginx 1 5
vmstat -w 1 6

MASTER=$(systemctl show nginx -p MainPID --value)
WORKERS=$(pgrep -P "$MASTER" -d,)
perf record -F 49 -g -p "$WORKERS" -- sleep 10
perf report --stdio --no-children -g none

The key observation was that nginx workers consumed substantial user-space CPU while CPU steal was relatively small. The measurements did not support sustained disk wait or active swapping as the primary explanation. The process-level view told me which program was busy; perf helped establish what it was doing.

One sample attributed roughly a third of sampled CPU activity to pcre_exec, with additional time in ngx_http_regex_exec and ngx_regex_exec. These are the functions expected when nginx executes regular expressions through PCRE. The profile did not prove which individual redirect map was responsible, but it made repeated regex evaluation a much stronger explanation than a problem with static HTML rendering.

The hidden cost of sequential regex entries in nginx map

An nginx map is not inherently slow. Literal string keys can be found efficiently, while regex entries are considered in configured order after the higher-priority matching categories. Map variables are evaluated when referenced, so a large regex map matters when its output is consumed on a frequent request path. An existing canonical image that matches none of the historical aliases can pay for many unsuccessful comparisons before nginx serves its bytes.

This distinction also explains why counting every location ~ block would have been misleading. Regex location selection and regex evaluation inside map are different mechanisms. Profiling identifies the expensive class of work; inspecting the request path and the variable consumers identifies where that work is triggered.

Further isolation revealed that the media lists were not the only source. A separate set of pagination page redirects also accounted for substantial regex work when its map was evaluated. Optimizing images alone would have left that independent cost in place.

Page redirects: one pagination pattern, but thousands of exact destinations

The page rules were repetitive: paths differed by an old identifier, and the end of the path matched a pagination pattern such as /topics/old-a/page/99. A tempting rewrite would extract 99 and append it to a new slug. That would have been wrong. Some historical pagination rules deliberately mapped every requested page number to a fixed final page, for example /topics/current-a/page/7, regardless of whether the source requested page 3 or page 99.

There was another important constraint: nginx gives exact map keys priority over regexes. Some exact entries overrode what the general pagination rule would do. Others explicitly mapped to an empty string to prevent a redirect for an already-canonical path. Testing only whether a returned destination was nonempty would lose the distinction between no exact match and an exact match whose value is empty.

The replacement separated path recognition from destination selection. The following is a reduced, synthetic illustration of the nginx http-level maps:

# http context: synthetic page aliases
map $uri $normalized_path {
    default $uri;
    ~^(.+)/$ $1;
}

map $normalized_path $exact_target {
    default "__NO_EXACT__";
    /topics/old-a        /topics/current-a;
    /topics/old-a/page/2 /topics/current-a/page/2;
    /topics/old-b/page/2 "";
}

map $normalized_path $pagination_key {
    default "";
    ~^/(?<old_root>topics/[a-z0-9-]+)/page/[1-9][0-9]*$ /$old_root;
}

map $pagination_key $pagination_target {
    default "";
    /topics/old-a /topics/current-a/page/7;
    /topics/old-b /topics/current-b/page/6;
}

map $exact_target $redirect_target {
    default $exact_target;
    __NO_EXACT__ $pagination_target;
}

The first map retains trailing-slash normalization. The second stores exact redirects and explicit empty overrides, with a sentinel meaning that no exact entry exists. The third uses a single regex to extract a pagination root. The fourth resolves that root through exact-key lookup to its original fixed destination. Finally, the selector honors any exact match, including the empty override, before considering the pagination result.

The redirecting server can then use the resulting $redirect_target only when it is nonempty, preserving the original HTTP status and appending $is_args$args when the existing policy preserves query strings. The sentinel must be reserved and validated so it can never collide with a real destination. The sample uses neutral paths; the production generator had to preserve its own complete mapping inventory and existing precedence.

Case behavior is easy to miss in this design. Nginx compares literal map string keys without regard to case, whereas regexes written with ~ are case-sensitive. Therefore a replacement cannot casually lowercase all URLs, or turn a ~ rule into ~*, and call the result equivalent. It must reproduce the original matching semantics.

Image and video redirects: parse once, then look up the old key

The media rules offered a similarly useful structure. A legacy image path had a gallery identifier in both its directory and filename, with an optional numeric suffix: /old-gallery/old-gallery-17.avif. Its destination reused that suffix but replaced the directory and filename prefix. Generating a regex for every old gallery and every suffix form wasted CPU on comparisons that shared the same grammar.

A more efficient map extracts the identifier and optional suffix with one regex, then uses a literal-key lookup for the new prefix:

# http context: synthetic AVIF rename inventory
map $uri $legacy_image_key {
    default "";
    ~^/(?<old_id>[a-z0-9-]+)/\k<old_id>(?<image_number>-[0-9]+)?\.avif$ $old_id;
}

map $legacy_image_key $new_image_prefix {
    default "";
    old-gallery /new-gallery/new-gallery;
    old-set     /new-set/new-set;
}

# A recognized alias now has a target candidate:
# $new_image_prefix$image_number.avif
# Existing-file checks and the actual 301 remain
# in the site's media-serving configuration.

For a recognized alias, /old-gallery/old-gallery-17.avif produces the candidate /new-gallery/new-gallery-17.avif. This is the lookup mechanism, not a complete serving policy. In the actual deployment, existing-file priority, destination-existence checks, and the 301 decision remained part of the media-serving configuration. An unconditional 301 in a simplified example would have been an incorrect substitute if the destination file did not exist.

Video redirects used a corresponding exact-key table behind a single filename-shape regex. The existing WebP compatibility path, which normalized its historical alias lookup to the image mapping, also had to remain intact. A media optimization is only successful if current files still return the correct bytes and headers, and following an old video alias still supports 206 Partial Content for range requests.

These examples work only because the historical inventories followed a predictable filename grammar. If arbitrary individual files were renamed independently, the safe design would use exact per-file keys, a generated index or another bounded lookup—not pretend that one regex can reconstruct destinations that have no common pattern.

What happened to the separate 410 map

Another part of the configuration explicitly enumerated retired page patterns solely to return 410 Gone. That special map was removed after verifying that the existing static-file routing policy already returned 410 for genuinely missing pages. The historical retirement metadata remained available for validation; only the redundant request-time matching was removed.

This is a configuration-specific decision, not a default behavior of nginx. A bare try_files often ends in 404 unless configured otherwise. Removing an explicit 410 rule is safe only if the actual server's missing-resource path still produces the required 410, including for retired pagination URLs and any internal error-page handling. That condition was checked with real HTTP requests before the change was accepted.

How to prove that a faster redirect map is the same redirect map

A syntactically valid nginx configuration can still silently break thousands of historical links. The replacement therefore used the original rule inventories as independent correctness inputs, not as a set of destinations reconstructed from the optimized output. Generated lookup tables were checked for duplicate keys, unsupported expressions, inconsistent image prefixes and stale generated files. Any rule that could not be represented safely had to fail generation rather than disappear.

The test matrix exercised exact page aliases, canonical empty overrides, overlapping pagination rules, fixed pagination caps, valid and invalid page numbers, trailing slashes, case variants and query strings. For media, it covered base and numbered images, suffixes containing leading zeros, identifiers ending in digits, nested destination paths, WebP compatibility and original video aliases. Where file serving mattered, the tests used actual readable fixtures and compared response bodies, redirects, cache-related headers and video byte ranges.

Most importantly, these were real nginx HTTP checks, not only string comparisons in JavaScript. The new configuration was exercised across the generated request matrix, and a separate set of requests was checked against the original PCRE-based configuration. The reported result was zero unintended response differences. Production smoke checks subsequently confirmed that the optimized includes were active and that the former long regex tables were not.

A controlled benchmark separated the improvement from changing traffic

Production CPU graphs improved substantially after deployment, but request volume and request mix also changed. Comparing one busy sample with a later quiet sample would exaggerate what could be attributed to the configuration change.

To isolate the lookup cost, an independent benchmark used the same nginx binary and repeated the same mixed sequence against original and optimized configurations. The sequence included canonical pages, historical page aliases, pagination aliases, missing pages, canonical images, historical image and video aliases, and missing media. Runs were interleaved in the order old, new, new, old; response statuses and Location values matched.

For that controlled workload, the optimized maps consumed less than one hundredth as much nginx worker CPU time as the original regex-heavy maps, with the result reproduced on repeat runs. This is a strong measurement of the redirect-processing change under that test mix. It is not a claim that every production request became 100 times faster, or that overall server CPU would fall by the same ratio under arbitrary traffic.

Later system checks found nginx using little CPU, with low disk pressure and ample processor idle time. The earlier PCRE hotspot no longer dominated the available post-change samples; at such low utilization those samples were sparse, so their per-function percentages should not be overinterpreted. The controlled comparison, parity tests and successful deployment are the stronger evidence for the fix.

A safer workflow for large nginx redirect migrations

For another site with many old URLs, I would keep the migration mechanical: retain the original rule inventory, identify the small set of shared path grammars, compile each grammar into a bounded regex, and store destinations as literal-key maps. Treat exact canonical overrides, HTTP status codes, existing-file checks, query strings, host canonicalization and case sensitivity as public behavior, not incidental implementation details.

Then validate the complete generated configuration with nginx -t, compare old and new behavior through real nginx, benchmark identical requests, and deploy with a restorable backup and post-reload checks. If a redirect cannot be represented by the structural scheme, retain a narrowly scoped exception or use an exact per-URL entry rather than silently dropping it.

The useful diagnostic shift was recognizing that static delivery and cheap routing are separate properties. Next.js had already done its rendering work, and nginx could serve files efficiently. The missing optimization was the lookup performed before serving those files. Keeping the old links was compatible with making that lookup fast.

For the exact precedence and evaluation rules, see the official nginx documentation for the map module and HTTP core location selection.