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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

NGINX if is a conditional from the ngx_http_rewrite_module, not a general-purpose configuration language. Put the condition in parentheses and use rewrite-module actions inside the braces. For example, this rejects POST requests while leaving normal content handling outside the conditional:

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

Use if for a small, immediate response or rewrite. For derived values, file selection, or host-wide routing, map, try_files, and separate server blocks are safer and easier to reason about.

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

What an NGINX if block does

NGINX evaluates rewrite-module directives in a request-processing phase. An if condition is written in parentheses, followed by a block containing directives that the rewrite module supports:

if (condition) {
    rewrite-or-response-directive;
}

The directive is valid in both server and location contexts. At the server level, rewrite directives run before NGINX selects a location. After a location is selected, location-level rewrite directives run there. If a rewrite changes the URI and requests another location lookup, this process can repeat, but NGINX limits rewrite cycles to 10 iterations.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.

That execution model explains both the usefulness and the danger of if: it is excellent for a narrowly scoped rewrite decision, but it is not an all-purpose programming construct for configuring proxying, content handlers, or an entire request pipeline.

Condition syntax you can use

NGINX supports four practical categories of tests inside an if. The condition must be enclosed in parentheses.

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.

Test whether a variable is true

If you put a variable by itself in the condition, NGINX treats an empty string or the value 0 as false. Any other value is true.

if ($some_flag) {
    return 204;
}

This form is useful when another directive has already produced a flag variable. Make sure the variable can actually be empty or zero when you want the condition to fail; a nonempty string such as false is still truthy.

Compare a variable with a string

Use = for equality and != for inequality:

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

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

These comparisons are string comparisons. The value on the right is written directly in the configuration, while the value on the left is normally an NGINX variable.

Match a regular expression

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

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 #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
if ($request_uri ~ ^/old/(.*)$) {
    rewrite ^/old/(.*)$ /new/$1 permanent;
}

if ($http_user_agent ~* mobile) {
    return 302 /mobile$request_uri;
}

Keep the expression focused on the routing decision. A broad expression can match more requests than intended, and a rewrite that repeatedly produces another matching URI can consume the available rewrite cycles.

Check whether a file-system path exists

File tests use these operators:

  • -f and !-f test for a regular file or its absence.
  • -d and !-d test for a directory or its absence.
  • -e and !-e test for any existing path or its absence.
  • -x and !-x test whether a path is executable or is not executable.

For example, a file-existence test can be written against a path variable:

if (-f $request_filename) {
    return 200;
}

For ordinary static-file dispatch, however, try_files expresses this requirement more directly and avoids putting file selection logic in an if block.

What belongs inside the braces

Keep the body to rewrite-module actions whose purpose is to produce a response, change the URI, assign a rewrite variable, or control rewrite processing. Common examples are:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • return to send a status code, redirect, or short response immediately.
  • rewrite to transform a URI or redirect it.
  • set to assign a variable used by later rewrite logic.
  • break to stop rewrite processing in the current location when that behavior is intentional.

The NGINX-maintained “If Is Evil” guidance states: “The only 100% safe things which may be done inside if in a location context are: return …; rewrite … last;” Treat that as the conservative rule for location-level configuration. In particular, do not put proxying, content handlers, or other non-rewrite directives inside a location-level if merely because NGINX accepts the configuration.

A location-level if can create a separate configuration context. A directive that appears to inherit or combine with the surrounding location may therefore behave differently than expected. Keep the actual content handler outside the conditional and route requests to an explicit location or named fallback instead.

Rank #3
Sale
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black | LED mouse pad with 14 lighting modes, covers keyboard & mouse, anti-slip rubber base, waterproof surface, USB powered
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Useful if patterns

Reject a method before content handling

This is the simplest safe pattern: test the request method and return a status without invoking the location’s content handler.

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

    proxy_pass http://backend;
}

The conditional only decides the response. The proxy directive remains in the location, outside the block. If the endpoint should advertise allowed methods, add the appropriate response headers in the surrounding configuration rather than trying to turn the if into a complete request policy engine.

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

Redirect a legacy host

An immediate return can redirect a request while preserving its path and query string:

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

This works as a narrow response rule, but a separate server block is the clearer design for a canonical-host redirect because the host decision belongs to virtual-server routing rather than to a location’s rewrite logic.

Redirect an old URI shape

Use a regular expression when the old path contains a variable suffix that must be carried into the new path:

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

The permanent flag sends a permanent redirect. If the intent is to continue processing internally under a different location, use last instead and understand that NGINX will perform another location lookup. Use break only when processing should remain in the current location.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.

Why complex location-level if logic is risky

There are three recurring failure modes:

  • Context surprises: a location-level conditional can create a separate configuration context, so non-rewrite directives may no longer combine with the surrounding location as you expect.
  • Unexpected content handling: putting proxy, FastCGI, static, or other content directives inside a conditional can select an incomplete or unintended request handler.
  • Rewrite loops: a rewrite can trigger another location search and run rewrite directives again. NGINX stops after 10 rewrite iterations, but the resulting request can still fail or return an unexpected URI.

Use an if when the decision is local and the action is a direct rewrite-module response. When the decision controls content selection or combines several independent inputs, move the decision into a construct designed for that job.

Choose the right construct instead

Construct Decision type Configuration context New location lookup Typical action Directive-safety guidance
if Request variable, comparison, regular expression, or file test server or location Only when its rewrite changes the URI and uses a flow that requests another lookup Immediate response or rewrite Keep location-level bodies to rewrite-module actions, especially return and rewrite ... last
map Derived value from one or more variable matches http No; it creates a variable evaluated when used Set a flag or value consumed later by a location, upstream, or response rule Safer for multiple conditions because decision-making is separated from request handling
try_files Whether candidate files or directories exist server or location Yes, when it internally redirects to a matching path or fallback Serve a file, directory, or named fallback Use for static-file selection instead of a file-test if
Separate server block Host or virtual-server routing http configuration containing servers NGINX selects the appropriate server for the request Canonical-host redirect or host-specific handling Preferred for old-host redirects; keeps host routing out of location rewrites

Use map for derived values and multiple conditions

map creates a variable whose value depends on another variable’s value. It is declared at the http level, supports string and regular-expression matches, and evaluates the result when the mapped variable is used.

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

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

This example leaves one small if for the final response but moves the method matrix into a declarative map. The same pattern scales when the output must be reused by several locations or when matching involves more than one regular expression. The map itself does not invoke a content handler or perform a location lookup; it simply supplies a value to later configuration.

Use try_files for static-file selection

When the question is “does this request map to a file or directory, and what should happen if it does not?”, use try_files:

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;
}

NGINX checks the listed paths in order. If it finds a file or directory, processing continues with that match. If none exists, NGINX uses the configured fallback, here the named location @app. This keeps static serving and application proxying as explicit locations rather than embedding a content decision in an if.

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

Use separate server blocks for host redirects

For an old hostname that should permanently redirect to a canonical hostname, define a server dedicated to the old host:

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
server {
    listen 80;
    server_name old.example.com;
    return 301 https://new.example.com$request_uri;
}

The host is selected before location processing, so this arrangement avoids an if-based host rewrite and makes the redirect’s scope obvious. It also prevents the old host from accidentally reaching the normal content handler if the conditional is changed later.

Understand last, break, and rewrite cycles

last: rewrite and search again

Use last when the rewritten URI should be processed by a new location. NGINX performs another location lookup, then runs the rewrite phase for that new request cycle.

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

break: stay in the current location

Use break when rewrite processing should stop but the request should remain in the current location. This is different from last; choosing the wrong flag can leave the request in a location whose content handler was not intended for the rewritten URI.

The ten-iteration limit

Because a URI rewrite can start another cycle, NGINX limits this processing to 10 iterations. A configuration that reaches the limit usually has a rewrite that keeps matching its own output, two locations that rewrite back and forth, or a regular expression that is broader than intended. Make each rewrite’s input and output visibly different, and test a request that exercises the boundary.

Validate and test before deployment

  1. Save the configuration and run nginx -t. Fix syntax or context errors before reloading.
  2. Reload NGINX only after the test succeeds.
  3. Send representative requests for every branch: matching and nonmatching methods, hosts, URI patterns, file paths, and regex case variants.
  4. For redirects, inspect the status code and Location header, and verify that the path and query string are preserved when expected.
  5. For internal rewrites, confirm which location ultimately handles the request and that the rewrite does not repeat.
  6. Test a missing file, an existing directory, and an application fallback when using try_files.
  7. Check logs for unexpected status codes, repeated redirects, or a request that reaches the wrong upstream.

nginx -t checks configuration validity; it does not prove that the request-routing behavior matches your intention. Behavioral testing with representative requests is still required.

Troubleshoot common mistakes

The condition never matches

  • Check whether the variable is empty, zero, or carrying a different value than expected.
  • For string comparisons, verify exact spelling and case.
  • For regular expressions, first test the simplest matching path and then add complexity.
  • Remember that ~ is case-sensitive while ~* is case-insensitive.

The request reaches the wrong handler

Move proxying or other content directives out of the if. Put them in an explicit location, and use return, rewrite ... last, map, or try_files to route the request there.

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

A redirect loops

Compare the redirect target with the condition’s input. If the target still satisfies the same condition, the next request can redirect again. A host redirect is usually better implemented as a separate server block, and a path rewrite should have a pattern that excludes its final form.

A rewrite appears to do nothing

Check whether you used break when you needed a new location lookup. If the request must be handled by another location, use last and verify that the new URI actually matches that location.

Static files fall through unexpectedly

Replace a file-existence if with try_files and an explicit fallback. Confirm the order of candidate paths and that the fallback location has its own content handler.

A practical decision checklist

  • Is the rule a single request test with an immediate status or redirect? Use a small if with return.
  • Does a URI need to be transformed and processed by another location? Use rewrite ... last.
  • Does the rule combine many matches or produce a reusable flag? Define a map at http level.
  • Does the rule choose between files, directories, and an application fallback? Use try_files.
  • Does the rule distinguish hostnames? Use separate server blocks.
  • Would the block need proxying, FastCGI, static serving, or another content directive? Do not put that content handler inside the if.
  • Could the rewrite match its own output? Test for a loop and remember the 10-cycle limit.

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.