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.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
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.
Location precedence, in practical order
Nginx tests the request URI against all applicable location directives. The selection rules are deterministic:
- An exact match such as
location = /oldwins immediately. No other location, including a regular expression, can replace it. - If there is no exact match, Nginx records the longest matching prefix, such as
location /old/. - Regular-expression locations, written with
~or~*, are then evaluated in configuration order. The first matching regular expression normally takes precedence over the remembered prefix. - A longest prefix marked
^~, for examplelocation ^~ /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.
#1 Best Overall
Match the URI the client actually sends
Check all of these details before changing directives:
- Whether the request is
/oldor/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.
- Run
nginx -Twith the privileges required by your installation. This prints the complete expanded configuration, including files pulled in withinclude. Search the output for the intendedserver_name,listenport, every competinglocation, and the redirect directive. - 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. - 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.
- Validate syntax with
nginx -t. Do not reload until it reports a successful test. - 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.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #2
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
lastends 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.breakstops 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.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallExternal 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:
Rank #3
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.
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.
Rank #4
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.
A repeatable diagnostic procedure
- Capture the exact request URI, method, host, scheme, port, and query string.
- Run
nginx -Tand identify the selected server candidates and every matching exact, prefix,^~, and regex location. - Compare the URI with each pattern, paying particular attention to trailing slashes and case. Ignore the query string when reasoning about location selection.
- For a simple redirect, temporarily reduce the rule to an explicit
return 302so browser caching cannot hide the result. - If a regex or capture is necessary, test the same rule with both
lastandbreakonly when their different rematching behavior is intentional. Never use a flag by habit. - Inspect
try_files,index,error_page, proxy directives, and the upstream application’s response for a second internal change or redirect. - Validate with
nginx -t, reload, and make a request withcurl -Iorcurl -v. Record the status code,Locationheader, host, scheme, and trailing slash. - 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.
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.
Quick Recap
Final verification checklist
- The request reaches the intended
serverblock 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. returnis used for a direct client redirect, with the intended temporary or permanent status.rewriteuseslastonly when rematching is deliberate andbreakonly 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 -tsucceeds, and the correct instance is reloaded. curl -vconfirms 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.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problems




