Understanding Nginx Rewrite Inside Location: Break Flag

Abstract: Resolve Nginx rewrite loops and unexpected 404 errors by using the break flag to stop processing within the current location block.

Created: 2026-08-29 by
The break flag in Nginx rewrite rules stops the processing of further rewrite directives within the current location block and uses the modified URI for the next phase, such as file system lookup. It does not trigger a new location match or cause an internal redirect, which distinguishes it from the last flag. Understanding this distinction is critical for configuring URL rewrites correctly without creating infinite loops or unintended behavior.

How Rewrite Flags Work

Nginx processes configuration files sequentially, evaluating directives based on their context. The rewrite directive is powerful but can be confusing because its behavior changes depending on the flag used. When you place a rewrite rule inside a location block, the engine needs to know what to do with the new URI after the substitution. There are four main flags: last, break, redirect, and permanent. The two that operate internally are last and break. Confusing these two is a common source of 500 Internal Server Errors or unexpected 404 Not Found responses. When Nginx encounters a rewrite rule, it modifies the request URI. The flag determines how the server handles that modified URI. If you use break, the server stops executing any subsequent rewrite rules in the same location block. It then proceeds to the next phase of request processing, typically trying to find the file associated with the new URI on the disk. It does not restart the location matching process. This means the request stays within the same logical context unless the file lookup fails or leads elsewhere via other mechanisms like try_files.

The Break Flag Specifically

The break flag tells Nginx to stop processing the rewrite directives for the current request in the current context. After applying the rewrite, Nginx uses the rewritten URI to satisfy the request. For example, if you have a rule that maps /app to /index.php, using break will cause Nginx to look for /index.php in the document root immediately. It will not re-evaluate which location block should handle /index.php. This is particularly useful when you want to map multiple URLs to a single script or file without triggering additional rewrite rules that might be defined later in the configuration or in nested locations. It effectively localizes the rewrite logic to the current block. If you were to omit the flag, Nginx would continue checking for more rewrite rules in the same location, which could lead to performance issues or incorrect mappings if other rules exist. Consider a scenario where you have a complex set of rewrite rules for SEO-friendly URLs. You might want to normalize certain paths but ensure that the final mapping is handled by a specific PHP entry point. Using break ensures that once the path is normalized, the control passes directly to the file handler or proxy pass, bypassing any further potential rewrites. This creates a predictable flow of execution. For related configuration challenges, see Nginx Configuration Issue for troubleshooting general setup errors.

Difference Between Break and Last

The most critical distinction is between break and last. Many users assume they are interchangeable, but they behave fundamentally differently regarding location matching. The last flag stops the rewrite processing and causes Nginx to search for a new matching location block using the rewritten URI. This can result in the request being handled by a completely different location context. If you use last, Nginx essentially restarts the location matching algorithm. For instance, if you rewrite /old-page to /new-page with last, and you have a separate location /new-page block, Nginx will jump to that block and evaluate its rules. This can lead to recursive loops if not configured carefully. In contrast, break keeps the request in the original location block's scope for the purpose of locating the resource. Using last is appropriate when you need to redirect the request to a different logical section of your configuration. Using break is appropriate when you just want to modify the URI for the current handler. A common mistake is using last when break is intended, which can cause performance degradation due to repeated location matching or even infinite loops if the new location contains similar rewrite rules.

Common Pitfalls and Best Practices

One frequent error is placing rewrite rules in the wrong context. Rules placed in the server block apply to all requests, while those in location blocks only apply to specific paths. Using break in a server block can have wide-ranging effects. Always test your configuration with nginx -t before reloading. Another pitfall involves the order of rules. Nginx evaluates rewrite rules in the order they appear. If you have a catch-all rule at the end of a location block, earlier rules with break will prevent it from ever executing. Ensure your most specific rules come first. Also, be aware that break does not stop the execution of other non-rewrite directives like proxy_pass or root. It only halts the rewrite module's processing. For insights on handling 404 errors during path resolution, refer to NGINX X-Accel-Redirect 404 Error: Path Config Seems Correct.

Example Configuration

Here is a typical configuration demonstrating the use of the break flag. This setup redirects all requests starting with /api to a backend service, but first normalizes the URL structure.
server {
    listen 80;
    server_name example.com;

    location /api/ {
        # Normalize the URI by removing query parameters for logging purposes
        rewrite ^/api/(.*)$ /api/$1 break;

        # Proxy the request to the backend
        proxy_pass http://backend_server;
    }
}
In this example, the rewrite directive modifies the URI but does not change the location context. The request continues to be handled by the location /api/ block and is proxied accordingly. If last were used, Nginx might try to find a new location block for the rewritten URI, potentially failing if no such block exists.

Frequently Asked Questions

Does break flag work in server context?

Yes, the break flag works in the server context as well as in location blocks. However, using it in the server context affects all requests processed by that server, so it should be used with caution to avoid unintended side effects on unrelated virtual hosts or paths.

What happens if I use last instead of break?

Using last causes Nginx to restart the location matching process with the rewritten URI. This means the request may be handled by a different location block than the one containing the rewrite rule. This can lead to different processing logic or errors if the new location does not exist or is misconfigured.

Can break cause infinite loops?

No, the break flag itself does not cause infinite loops because it stops further rewrite processing in the current context. Infinite loops are more commonly caused by using last incorrectly, where the rewritten URI matches the same location block again, causing repeated re-matching.

Should I use break or last for permanent redirects?

Neither break nor last is suitable for permanent redirects. For permanent redirects (HTTP 301), you should use the permanent flag. For temporary redirects (HTTP 302), use the redirect flag. These flags send an HTTP response to the client, whereas break and last are for internal processing.

Does break affect proxy_pass directives?

No, the break flag only stops the processing of rewrite directives. It does not halt other directives like proxy_pass, root, or alias. The request will continue to the next phase of processing, such as attempting to serve a file or proxying to a backend, based on the rewritten URI.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More