Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk9 min

How to Fix an Nginx Location Block That Is Not Redirecting

A practical guide to finding why Nginx ignores a location redirect, selecting the right server and location, and choosing safely between return and rewrite.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If an Nginx location block does not redirect, the usual cause is not the return directive itself. Nginx may have selected a different server or location, your request may not match the URI pattern you wrote, or a later internal redirect, proxy, or application response may replace what you expected. Confirm the active configuration, understand location precedence, then use an explicit return for a client-visible redirect. Reserve rewrite for conditional transformations that genuinely need pattern matching.

What Nginx does before it redirects

Nginx first chooses a server block using the connection’s listen address and port and the request’s Host header. Only after that does it select a location. A perfectly written redirect in the wrong server block will therefore appear to be ignored.

As an Amazon Associate I earn from qualifying purchases.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Location precedence, in practical order

Nginx tests the request URI against all applicable location directives. The selection rules are deterministic:

  1. An exact match such as location = /old wins immediately. No other location, including a regular expression, can replace it.
  2. If there is no exact match, Nginx records the longest matching prefix, such as location /old/.
  3. Regular-expression locations, written with ~ or ~*, are then evaluated in configuration order. The first matching regular expression normally takes precedence over the remembered prefix.
  4. A longest prefix marked ^~, for example location ^~ /old/, prevents regular-expression locations from overriding that prefix.

This means that adding a regex location elsewhere in an included file can change which block handles a request. It also means that location /old and location /old/ are different patterns. The query string is not used for location matching: /old?ref=mail is matched as the URI /old.

Match the URI the client actually sends

Check all of these details before changing directives:

  • Whether the request is /old or /old/.
  • Whether the path contains a filename or an extra segment, such as /old/file.html.
  • Case differences when a case-sensitive prefix or regex is used.
  • Percent-encoding and normalized path segments.
  • The request method. A browser’s GET test does not prove that a POST or other method will behave identically.

Inspect the configuration Nginx is really using

Editing a file is not the same as changing the running instance. Distribution packages, containers, control panels, and custom builds can use different configuration roots or even different Nginx binaries.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Run nginx -T with the privileges required by your installation. This prints the complete expanded configuration, including files pulled in with include. Search the output for the intended server_name, listen port, every competing location, and the redirect directive.
  2. Run nginx -V. Its configure arguments expose paths such as the prefix, configuration file, error-log path, and module build options. Use the same binary and configuration path when testing and reloading.
  3. Compare the request’s host and port with the selected server. A request sent to an IP address, an alternate hostname, or HTTPS instead of HTTP may enter a different block.
  4. Validate syntax with nginx -t. Do not reload until it reports a successful test.
  5. Reload the same Nginx instance whose configuration you inspected. A successful reload of another installation does not affect the process serving the request.

If nginx -T shows a redirect that is absent from the file you edited, an include or generated configuration is supplying it. If it does not show your change, you are editing the wrong file, using a different configuration root, or the file is not included.

Use return for a straightforward redirect

For a client-visible redirect, Nginx documentation describes return as the easiest approach. It can be used in server or location context and sends the status and Location header directly to the client.

Exact-path redirect

server {
    listen 80;
    server_name example.com;

    location = /old {
        return 301 https://example.com/new;
    }
}

The exact modifier limits the rule to /old. A request for /old/ or /old/page will not match it. Add separate locations or use a prefix when those paths should also redirect.

Prefix redirect

location ^~ /docs-old/ {
    return 301 https://example.com/docs-new/;
}

This handles the prefix and its descendants while ensuring a regex location cannot take precedence. Choose the target carefully: a fixed target sends every matching request to the same URI. If the path suffix must be retained, construct the destination deliberately rather than assuming Nginx will append it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preserve the query string when needed

location = /old {
    return 301 https://example.com/new$is_args$args;
}

$is_args contributes a question mark only when arguments exist, and $args carries the original query string. Test this behavior with both a request that has no query and one that has several parameters.

Select the status code intentionally

Status Use Important behavior
301 Permanent move Browsers and caches may retain it, so do not use it while a rule is still being developed.
302 Temporary redirect Useful for testing or a short-lived destination; clients commonly change a non-GET method to GET.
307 Temporary redirect with method preservation Suitable when a POST, PUT, or other method must be sent to the new URI unchanged.
308 Permanent redirect with method preservation Use only when the permanent status and method-preserving behavior are both intended.

Use a temporary response while verifying the rule. Switch to a permanent status only after the destination and scope are stable.

Use rewrite only when matching logic is required

rewrite is conditional: it evaluates a regular expression, builds a replacement URI, and then applies a flag. It is useful when captures or several conditions determine the target, but it introduces another opportunity for a location to be selected.

last versus break

  • last ends the current rewrite set and starts a new location search using the rewritten URI. This is appropriate when the new URI should be handled by another location.
  • break stops processing the current rewrite directives but keeps the request in the current location. Downstream directives in that location continue to apply.
location ~ ^/legacy/(.*)$ {
    rewrite ^/legacy/(.*)$ /new/$1 last;
}

location /new/ {
    proxy_pass http://app_backend;
}

Here, last intentionally rematches the generated /new/ URI. If the rewrite target can match the original regular expression again, the request may loop until Nginx returns an internal-redirection error. Avoid rewriting to a URI that re-enters the same rule, and test both the matching and non-matching paths.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

External versus internal results

A rewrite that produces an absolute HTTP or HTTPS URL can cause a client redirect. A rewrite to a local URI normally performs an internal change: the browser does not receive a redirect and Nginx continues processing the new URI. If the reader must see a new address, an explicit return is usually clearer and easier to diagnose.

Why try_files, index, and error_page can change the outcome

Not every URI change is a redirect response. try_files checks filesystem paths and can internally redirect to its final argument. For example:

location / {
    try_files $uri $uri/ /index.php?$query_string;
}

A request that does not correspond to a file may therefore be handled by /index.php rather than by the location you expected. The browser sees no 3xx response unless another directive generates one.

index can cause directory processing to select an index resource, while error_page can internally route an error to another URI. A proxied application can also return its own 3xx response. When the status or Location header is unexpected, inspect all of these paths rather than assuming the first matching location produced the final response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common causes and precise fixes

The request reaches another server block

Verify the exact Host header, listen port, and TLS server. Add a temporary diagnostic header or distinctive status only while testing, then remove it. The expanded output from nginx -T is the authoritative way to see duplicate names, default servers, and included blocks.

An exact and prefix pattern do not cover the same URLs

location = /download does not match /download/. Conversely, a prefix such as location /download/ does not match the path without the slash. Decide whether both forms should redirect and define each behavior explicitly.

A regex location wins over a prefix

If a regular expression matches before the request reaches your prefix block, move the rule, make the intended prefix ^~, or replace the ambiguous rules with an exact match. Remember that regex locations are evaluated in configuration order, including the order created by include files.

The configuration was not loaded

Run nginx -t, then reload the same process identified through nginx -V. If a container or service manager is involved, execute the commands in the environment that owns the serving process. Confirm the new configuration appears in nginx -T after reloading.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A cached permanent redirect is masking a fix

Browsers and intermediary caches can remember 301 and 308 responses. Test with a new temporary status during development, use a separate test hostname when possible, and inspect the response with curl rather than relying only on browser behavior.

The upstream application sends the redirect

Use response headers and logs to determine whether Nginx or the upstream generated the Location header. Review proxy settings, application base-URL settings, and HTTP-to-HTTPS logic. A correct Nginx location cannot prevent an upstream from returning its own response unless proxy behavior is explicitly configured to do so.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

A repeatable diagnostic procedure

  1. Capture the exact request URI, method, host, scheme, port, and query string.
  2. Run nginx -T and identify the selected server candidates and every matching exact, prefix, ^~, and regex location.
  3. Compare the URI with each pattern, paying particular attention to trailing slashes and case. Ignore the query string when reasoning about location selection.
  4. For a simple redirect, temporarily reduce the rule to an explicit return 302 so browser caching cannot hide the result.
  5. If a regex or capture is necessary, test the same rule with both last and break only when their different rematching behavior is intentional. Never use a flag by habit.
  6. Inspect try_files, index, error_page, proxy directives, and the upstream application’s response for a second internal change or redirect.
  7. Validate with nginx -t, reload, and make a request with curl -I or curl -v. Record the status code, Location header, host, scheme, and trailing slash.
  8. Repeat with a query string and, when relevant, the original non-GET method. This catches lost arguments and method-changing temporary redirects.

Read the logs for the location that actually handled the request

The error_log directive sets the error log and can be declared at the main, HTTP, server, or location level. A setting inside a server or location overrides inherited logging settings, so the file you are watching may not be the file receiving the relevant message.

Tail the configured access and error logs while making one test request. The access log confirms the final status and request URI; the error log can show rewrite cycles, failed file checks, upstream responses, and internal redirects. If more detail is required and the build supports it, temporarily increase the error_log level or enable debug logging for a controlled client address. Restore the normal level afterward because debug logging is verbose.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Reliable redirect patterns

Redirect one legacy URL

location = /old-product {
    return 302 https://example.com/new-product;
}

Use this while testing, then change to 301 after confirming the destination.

Redirect a directory and retain its query string

location ^~ /old-section/ {
    return 301 https://example.com/new-section/$is_args$args;
}

This example sends every path under the old prefix to one destination. If each old suffix needs a corresponding new suffix, use a carefully constrained regex rewrite instead and verify that it cannot match its own output.

Force HTTP to HTTPS at server scope

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}

Keeping the scheme redirect in the HTTP server block avoids scattering it across content locations. The HTTPS server should then contain the content locations for the secure host.

Final verification checklist

  • The request reaches the intended server block for its host, port, and scheme.
  • The location pattern matches the exact URI, including slash and case behavior.
  • An exact match, earlier regex, or ^~ prefix is not selecting a different block.
  • return is used for a direct client redirect, with the intended temporary or permanent status.
  • rewrite uses last only when rematching is deliberate and break only when processing should remain local.
  • No try_files, index, error_page, proxy, or upstream application changes the request afterward.
  • The edited file appears in nginx -T, nginx -t succeeds, and the correct instance is reloaded.
  • curl -v confirms the expected status, Location, host, scheme, path, and query-string behavior.
  • Access and error logs identify the handler and show no internal redirect cycle.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.