DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk9 min

Nginx Rewrite Rules: How to Rewrite URLs on Your Server

A practical NGINX guide to URL rewriting: choose between return, rewrite, and try_files; understand last versus break; build canonical redirects and front-controller fallbacks; and troubleshoot loops.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use return for a fixed redirect, rewrite for a regular-expression URI transformation, and try_files when the decision depends on whether a file or directory exists. Choosing the directive that matches the job keeps your NGINX configuration predictable, avoids redirect loops, and makes migrations from Apache easier.

What NGINX URL rewriting actually does

NGINX’s ngx_http_rewrite_module changes a request URI with PCRE regular expressions, returns redirects or other status responses, and can select different configuration paths conditionally. Rewrite directives can run in a server context and inside a location. When a rule changes the URI, NGINX may perform another location search and then process the new location’s directives.

As an Amazon Associate I earn from qualifying purchases.

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

That search is not unlimited: NGINX permits a maximum of 10 rewrite or internal-redirection cycles for one request. A rule that continually changes a URI, or repeatedly sends a request back to the same location, eventually fails with an internal redirection or rewrite-cycle error. Design each rule with a clear stopping point.

Choose the right directive first

Directive Best use Client sees a new URL? How matching works Main risk
return Known redirect, canonical host, HTTP-to-HTTPS redirect, blocked path, or fixed status response Usually yes when a 3xx status and URL are returned No regular expression required Redirecting to the wrong host or scheme, especially behind a TLS-terminating proxy
rewrite Regex-based path transformation or conditional URI replacement Only with an external redirect result; otherwise no PCRE regular expression and replacement string Unexpected captures, rule ordering, or loops caused by last
try_files Serve an existing file or directory, show a maintenance page, or fall through to an application front controller No, unless the fallback itself returns a redirect Checks filesystem paths in order Incorrect root, permissions, or a fallback that sends requests back into the same check

The NGINX community guidance describes return as the simpler general-purpose directive and recommends it instead of rewrite when a regular expression is unnecessary. A regex should solve a real pattern-matching problem, not merely make a fixed redirect look more complicated.

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Use return for fixed redirects and responses

return accepts a status code and, where appropriate, a URL or response text. It is the clearest choice when every request in a server block has the same outcome.

Canonical host redirect

Put the noncanonical hostname in its own server block. The request URI is preserved by $request_uri, including its path and query string.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server {
    listen 80;
    server_name example.org;

    return 301 http://www.example.org$request_uri;
}

Choose the canonical scheme and hostname deliberately. If HTTPS is terminated by a load balancer or another proxy before the request reaches NGINX, confirm which forwarded scheme and host variables are trusted; otherwise an apparently simple redirect can point users to the wrong protocol or create a loop.

HTTP-to-HTTPS redirect

A separate HTTP server block keeps the redirect unconditional and prevents application locations from handling traffic that should never be served over HTTP.

server {
    listen 80;
    server_name example.org www.example.org;

    return 301 https://www.example.org$request_uri;
}

Use a permanent 301 only after the destination is correct. Browsers, crawlers, and intermediate caches can retain a 301, making mistakes harder to reverse. During a temporary migration or test, a 302 is easier to change.

Fixed status responses

The same directive can reject a path or deliberately return a status without an application request.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
location = /private-health-check {
    return 403;
}

location = /maintenance {
    return 503 "Temporarily unavailable";
}

Use an exact-match location (=) when only one URI should receive the response. A broader prefix can unintentionally affect child paths.

Understand rewrite syntax and flags

The official form is:

rewrite regex replacement [flag];

The regular expression is matched against the request URI. Captured groups can be inserted in the replacement as $1, $2, and so on. If the replacement starts with http://, https://, or $scheme, NGINX generates an external redirect. Otherwise, the URI is changed internally.

What each flag means

Flag Result Use it when
last Stops the current rewrite set and starts a new location search using the changed URI The rewritten URI should be handled by another location or by the normal location-selection process
break Stops the current rewrite set but does not start a new location search The current location should continue handling the changed URI
redirect Returns a temporary 302 redirect The client should request the replacement URL, but the change is not permanent
permanent Returns a permanent 301 redirect The old public URL has been permanently replaced

Without a redirect flag, a rewrite normally changes the URI internally. A last rewrite can therefore trigger another location search, while break keeps processing in the current location. Selecting the wrong one is a common cause of loops or of a request missing the configuration you expected it to use.

Ordered regex transformations

Rewrite directives execute in the order written. Put narrow, unambiguous patterns before broad patterns that could also match them.

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 /download/ {
    rewrite ^(/download/.*)/media/(.*)..*$ $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(.*)..*$ $1/mp3/$2.ra last;
}

For example, a path ending in a file extension under media is transformed to an mp3 path, while a matching path under audio is transformed to an ra path. The captures preserve the portions represented by the two parenthesized groups.

When to choose break instead

If the transformed URI should remain under the current location’s processing, use break after verifying that the location’s handlers can serve it. This avoids an unnecessary location search and can prevent a rule from re-entering the same location. Do not substitute break merely to hide a loop: first determine which location is supposed to handle the resulting URI.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Use try_files for files, directories, and front controllers

try_files checks candidate filesystem paths in sequence. It is usually clearer than a chain of regular expressions when the real question is “does this file or directory exist?” The final argument can be a URI, a named location, or an application handoff.

location / {
    try_files $uri $uri/ @app;
}

location @app {
    proxy_pass http://backend;
}

Here NGINX first tests the path represented by $uri, then the directory form $uri/. If neither exists, it transfers the request to the named location @app, which proxies it to the backend. Replace the proxy handler with FastCGI or another upstream protocol when that is what the application requires.

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

A fuller static and maintenance sequence

A site that has a maintenance file, extensionless pages, and an application fallback can express those checks in a readable order:

location / {
    try_files /maintenance.html $uri $uri/index.html $uri.html @app;
}

location @app {
    proxy_pass http://backend;
}

Place the maintenance check first only when you intentionally want it to take precedence. Otherwise, a maintenance file can make every request serve the maintenance page even while valid static files exist. The exact filesystem root and permissions are part of the server’s deployment configuration; a syntactically valid directive cannot find a file outside the configured root or a path NGINX cannot read.

How NGINX processes rewrites

  1. Server-level processing: NGINX evaluates directives in the selected server context, including unconditional redirects and server-level rewrites.
  2. Location selection: NGINX chooses a location for the current URI and runs the directives in that location.
  3. URI change: A rewrite can replace the URI internally or return a redirect to the client.
  4. Possible new search: If the rule uses last, NGINX searches for a location again using the new URI. The cycle can repeat, but no more than 10 times.
  5. Final handler: Once no further rewrite requires a search, NGINX serves the file, returns a response, or passes the request to the configured application handler.

This sequence explains why a rule that appears correct in isolation can behave differently inside a location. Always inspect the resulting URI and the location that should own it.

301 versus 302: choose the status deliberately

A 301 communicates that a URL has moved permanently; a 302 communicates a temporary redirect. Both are external responses, so the browser makes another request. Permanent redirects may be cached and retained by crawlers, while temporary redirects are more suitable while testing or while a destination is only provisional. Neither status makes an internal rewrite: the client URL changes only when NGINX returns a redirect response.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Do not use a 301 as a debugging shortcut. Test the destination with a temporary response first when you are unsure about hostnames, ports, paths, or HTTPS termination, then change the status once the behavior is confirmed.

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

Converting Apache .htaccess rules to NGINX

NGINX does not process .htaccess files. Its configuration is loaded centrally, so an Apache rule must be translated into the appropriate server, location, and handler blocks rather than copied into a per-directory file.

Move host conditions into server blocks

Apache rules that branch on the hostname are often clearer as separate NGINX server blocks. One block can catch the old or noncanonical host and issue a return 301; the canonical block then serves the application. This avoids embedding host tests in every path rule.

Replace file-existence chains with try_files

Many Apache configurations test whether a file exists, then whether a directory exists, and finally send the request to a front controller. In NGINX, express that sequence directly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
location / {
    try_files $uri $uri/ @app;
}

location @app {
    proxy_pass http://backend;
}

Use a FastCGI handler instead of proxy_pass when the application runs through FastCGI. The fallback mechanism is the same; only the application handoff changes.

Translate only genuine pattern rules with regex

An Apache rule that maps many old paths to a structured new path may need rewrite. Preserve its captures deliberately, check whether the old rule performed an external redirect or an internal handoff, and choose permanent, redirect, last, or break to match that behavior. Do not assume that Apache’s per-directory path is identical to the URI NGINX matches.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

For a large legacy configuration, a dedicated rewrite reference such as the rewrite-rule chapter in Mastering NGINX can provide additional translation patterns, but every converted rule still needs testing in the target server layout.

Debugging rewrite failures

Validate before reloading

Run the installed NGINX binary’s configuration test before applying changes:

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.
nginx -t

Only reload after the test reports valid syntax and a successful configuration load. A syntax check catches malformed directives and missing includes; it does not prove that a redirect destination, regular expression, filesystem root, or upstream is logically correct.

Recognize a rewrite loop

Symptoms include a browser reporting too many redirects, repeated 3xx responses in a command-line client, or an error-log message describing a rewrite or internal-redirection cycle. Inspect every rule that uses last, the URI it produces, and the location selected on the next pass. Check whether the replacement URI still matches the original rule. Add a terminating condition, narrow the regular expression, or use break when a new location search is not required.

Check rule order

Because rewrite directives run sequentially, a general rule placed first can consume a request that a specific rule was meant to handle. Reorder from most specific to most general, and test requests that match exactly one rule as well as requests that could match several.

Separate redirect problems from application problems

Use a response-header client to see whether the client is receiving a 301 or 302, and follow the Location header one hop at a time. If NGINX returns the expected internal URI but the application produces an error, the rewrite may be correct and the problem may be in the upstream, document root, permissions, or application routing.

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

Account for deployment topology

Behavior can depend on the NGINX version, the modules compiled into it, the proxy or load-balancer arrangement, and whether TLS terminates before NGINX. Record the incoming host and scheme values used by your topology before writing canonical redirects.

A practical decision checklist

  • Is the destination fixed for every request? Use return in a dedicated server or location block.
  • Must a regular expression capture and transform part of the path? Use rewrite.
  • Does the decision depend on an existing file, directory, maintenance page, or front controller? Use try_files.
  • Should the changed URI be handled by another location? Use last.
  • Should the current location continue handling it? Consider break.
  • Is the client URL supposed to change? Return a 301 or 302; an internal rewrite alone does not change the address bar.
  • Could the replacement still match the same rule? Test for a loop before deployment.
  • Have you run nginx -t and inspected the error log after reloading?

Putting the pieces together

A maintainable configuration commonly has a small HTTP redirect server, a canonical HTTPS server, explicit locations for static assets, and one application fallback. Fixed host and scheme changes belong in return; pattern-based legacy URLs belong in narrowly scoped rewrite directives; file and directory checks belong in try_files. Keeping those responsibilities separate makes the configuration easier to audit and reduces the chance that a new rule will alter unrelated requests.

There is no authoritative universal latency, throughput, or search-ranking number that proves one of these directives is always faster or better. The reliable distinctions are their documented behavior: whether they redirect or rewrite internally, whether they use regex or filesystem checks, whether they start a new location search, and how they handle status codes and rewrite cycles.

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 *

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
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

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.