Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon 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 Use Conditional Logic Inside an Nginx if Block

NGINX if handles rewrite-time conditions—not general configuration branching. Learn its supported tests, safe directives, execution limits, and better alternatives for maps, files, and host redirects.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

NGINX if is a conditional from the ngx_http_rewrite_module, not a general-purpose configuration language. Put a condition in parentheses, then place rewrite-module actions in braces. A method check, for example, can reject every POST request in a location:

location / {
    if ($request_method = POST) {
        return 405;
    }
}

The condition can test a variable’s truthiness, compare strings, match a regular expression, or test whether a filesystem path exists. The important safety rule is to keep the block focused on response and rewrite actions. Do not put proxying or content-handler directives inside a location-level if; use map, try_files, explicit locations, or separate server blocks when those constructs describe the decision more accurately.

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.

What an NGINX if block actually does

The if directive is implemented by NGINX’s HTTP rewrite module. It is valid in both server and location contexts. NGINX evaluates the condition and, if it is true, processes the directives between the braces.

Its syntax is:

if (condition) {
    rewrite-module-directive;
}

The braces do not create a general programming-language branch in which any NGINX directive is safe. They create a rewrite-module configuration context. That distinction explains both the useful cases and the warnings surrounding if.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

A minimal conditional response

location / {
    if ($request_method = POST) {
        return 405;
    }

    # Normal content handling remains outside the if block.
}

For a matching POST request, return 405 ends request processing with HTTP status 405. Requests using other methods continue through the rest of the location configuration.

Condition forms supported by if

Use one of the documented condition forms below. The operator determines whether NGINX performs a truthiness test, a string comparison, a regular-expression match, or a filesystem test.

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

Variable truthiness

A variable by itself is true when it is neither an empty string nor the string 0. An empty value and 0 are false.

if ($maintenance_mode) {
    return 503;
}

This form is useful when another part of the configuration deliberately sets a flag variable. Because both an empty string and 0 evaluate as false, choose the variable’s values consistently rather than mixing arbitrary text, numbers, and empty values.

String comparison

Compare a variable with a literal value by using = or !=:

if ($request_method = POST) {
    return 405;
}

if ($host != www.example.com) {
    return 400;
}

The first condition is true only when $request_method is exactly POST. The second is true for every host value other than the stated string. Comparisons are useful for a small, direct decision involving one value; they become harder to maintain when many accepted values or combinations are involved.

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

Regular-expression matching

Use ~ for a case-sensitive regular-expression match and ~* for a case-insensitive match. Prefix either operator with ! to negate it: !~ and !~*.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
if ($request_uri ~ ^/old/(.*)$) {
    rewrite ^/old/(.*)$ /new/$1 permanent;
}

if ($host ~* ^api.) {
    return 403;
}

In the first example, a URI beginning with /old/ is rewritten to the corresponding /new/ path and sent as a permanent redirect. The expression captures the remainder of the path in $1. In the second example, the case-insensitive expression matches hosts whose value begins with api..

Negative forms let you reject or reroute values that do not match:

if ($request_uri !~ ^/public/) {
    return 404;
}

Keep regular expressions narrowly scoped. A pattern that is too broad can match more requests than intended, while a pattern that assumes a particular case can fail when the request value differs in capitalization.

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

Filesystem existence tests

NGINX also supports tests for paths on the server:

  • -f tests for a regular file; !-f is its negative form.
  • -d tests for a directory; !-d is its negative form.
  • -e tests whether the path exists; !-e is its negative form.
  • -x tests for an executable path; !-x is its negative form.
if (-f $request_filename) {
    return 200;
}

These tests inspect the path represented by the expression. For ordinary static-file selection, however, try_files communicates the intent more clearly and avoids putting file selection logic in an if.

What belongs inside the braces

Keep the body to rewrite-module directives such as return, rewrite, set, and break. The safest uses make an immediate response or perform a deliberate URI rewrite.

Rejecting a method

location /api/ {
    if ($request_method = POST) {
        return 405;
    }

    proxy_pass http://backend;
}

The conditional response is inside the block; the proxying directive remains in the location itself. This separation matters because content handling is not the purpose of the rewrite conditional.

Redirecting an old host

server {
    listen 443 ssl;
    server_name old.example.com;

    if ($host = old.example.com) {
        return 301 https://new.example.com$request_uri;
    }

    # Other server configuration follows outside the if.
}

This works as a response-only condition, but a dedicated server block is the clearer choice for a host-wide redirect; that alternative is shown below.

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.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Rewriting a URI

location / {
    if ($request_uri ~ ^/old/(.*)$) {
        rewrite ^/old/(.*)$ /new/$1 permanent;
    }
}

A rewrite can use a redirect flag such as permanent, as in the example, or can route internally. When the purpose is to select another location, use rewrite ... last. When processing should continue in the current location, use break.

“The only 100% safe things which may be done inside if in a location context are: return …; rewrite … last;”

— NGINX Wiki, “If Is Evil”

The quotation is intentionally narrow: it describes the safest location-level actions, not a promise that every other rewrite-module directive is invalid. Treat it as a design boundary. Put response and routing decisions in the conditional, and leave proxying, static content, FastCGI, and other content handlers outside it.

Why location-level if is considered unsafe

A location-level if can create a separate configuration context while NGINX builds the request-processing configuration. Some non-rewrite directives may be accepted syntactically, yet their behavior can be surprising because the resulting context is not equivalent to writing those directives directly in the location.

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

The practical failure mode is usually a conditional that appears to work for one request but interferes with content handling, proxying, or another location on a different path. Avoid embedding a proxy or content handler in the block:

# Avoid this pattern
location / {
    if ($request_method = POST) {
        proxy_pass http://backend;
    }
}

Instead, let the if return or rewrite, and place the content handler in an explicit location or named fallback. If the decision is really about a derived value, a filesystem choice, or a host name, use the construct designed for that decision rather than extending if into a general branch.

How rewrite processing is evaluated

NGINX first runs rewrite-module directives at the server level. It then searches for a location and runs the location-level rewrite directives. If a rewrite changes the URI, NGINX can perform another location lookup and repeat the cycle.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

last versus break

  • last deliberately starts a new location lookup after the rewrite. Use it when the rewritten URI should be handled by another location.
  • break stops rewrite processing for the current cycle and continues in the current location. Use it when the current location should keep handling the request.

NGINX limits rewrite processing to 10 iterations. A chain that keeps changing the URI can therefore stop after the limit instead of reaching the intended handler. Design rewrites so that the new URI leaves the matching condition, or route once to a stable named or explicit location.

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

Use map for derived values and multiple conditions

map creates a variable whose value depends on another variable. Define it at the http level, then use the resulting variable in a server or location. It supports string matches and regular-expression matches, and the mapped value is evaluated when the variable is used.

http {
    map $request_method $method_allowed {
        default 0;
        GET     1;
        HEAD    1;
    }

    server {
        if ($method_allowed = 0) {
            return 405;
        }
    }
}

Here, the mapping expresses the method policy in one place. The conditional only checks the derived flag and returns the response. Add more methods or match patterns in the map rather than building a long sequence of nested conditions.

Use try_files for file and directory selection

For static content, try_files is the purpose-built alternative to filesystem tests in an if. It checks the specified files or directories in order. If it finds a match, NGINX uses that result; if none matches, it internally redirects to the configured fallback.

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

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

The first location tests the requested URI as a file and then as a directory. If neither exists, processing goes to the named @app fallback, where the proxy directive is safely outside an if block.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use a separate server block for a host redirect

A host-wide redirect does not need a request-time condition in the destination server. Give the old host its own server block and return the redirect directly:

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

This makes host selection explicit and avoids evaluating a host condition for every request that reaches a broader server block. The rewrite-conversion guidance from NGINX describes an if-based host rewrite as wrong, cumbersome, and ineffective compared with a separate server.

Choosing between if, map, try_files, and server

Construct Decision input Configuration context Location lookup behavior Safe primary role
if Request variable, string, regular expression, or filesystem test server or location A URI rewrite can trigger another lookup; processing can repeat up to 10 cycles Return a response or perform a controlled rewrite
map A derived value based on a variable, string match, or regular expression http No lookup by itself; its variable is evaluated when used Compute a flag or value for later routing or response logic
try_files Whether candidate files or directories exist location Uses the first match or internally redirects to the fallback Select static content or a named application fallback
Separate server block Host name server Chooses the server configuration for the host Return a host-wide redirect directly

Use the smallest construct that matches the decision. A single method rejection is a good if. A reusable policy for several methods belongs in map. File selection belongs in try_files. A redirect for an entire old host belongs in its own server.

Putting the patterns together

The following configuration combines the constructs without putting a content handler inside a conditional:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
http {
    map $request_method $method_allowed {
        default 0;
        GET     1;
        HEAD    1;
    }

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

    server {
        listen 80;
        server_name example.com;

        location / {
            if ($method_allowed = 0) {
                return 405;
            }

            try_files $uri $uri/ @app;
        }

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

The old host is handled before it reaches the application server. The application server derives method policy with map, uses a response-only if, and delegates file selection and application handling to try_files and a named location.

Testing before deployment

Validate the configuration before reloading NGINX:

  1. Run nginx -t and resolve every syntax or context error it reports.
  2. Send representative requests for each branch: an allowed method, a rejected method, a matching URI, a nonmatching URI, an old host, and a new host.
  3. Check the status and destination for every redirect or rejection, and verify that requests falling through the condition still reach the intended location or named fallback.
  4. For rewrites, include a URI that could match again. Confirm that the rewritten URI becomes stable rather than starting an unintended chain.

Configuration validation proves that NGINX can parse the file; representative requests prove that the condition, rewrite, and fallback behavior match the intended request flow.

Troubleshooting common mistakes

The condition never matches

Check the operator and the exact value. A string comparison with = is not a regular-expression match, and a truthiness test treats both an empty string and 0 as false. For pattern matching, verify whether you need case-sensitive ~ or case-insensitive ~*, and whether the negative operator is the one you intended.

A rewrite reaches the wrong location

Inspect whether the rule uses last or break. last starts a new location lookup; break stays in the current location. Choose the flag according to where the rewritten request should be handled.

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

Requests loop or stop after several rewrites

Look for a rule whose replacement URI still satisfies its own condition or another rule in the chain. Rewrite processing is capped at 10 iterations, so make the destination unambiguously different from the source pattern or route once to a stable location.

Proxying behaves unexpectedly inside an if

Move proxy_pass and other content-handler directives outside the block. Keep the conditional to a response or rewrite, then use an explicit location or named fallback for proxying.

File checks are becoming complicated

Replace a series of existence tests with try_files. It expresses ordered file and directory checks and provides an explicit fallback when none exists.

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.