Process Flow - Conditional redirects with if
Request Received
Evaluate if condition
Redirect
End Request
Nginx checks the if condition on each request. If true, it redirects; if false, it serves the request normally.
server {
listen 80;
if ($host = 'old.example.com') {
return 301 https://new.example.com$request_uri;
}
}| Step | Request Host | Condition ($host = 'old.example.com') | Action | Result |
|---|---|---|---|---|
| 1 | old.example.com | True | return 301 redirect | Redirect to https://new.example.com$request_uri |
| 2 | new.example.com | False | serve normally | Serve requested content |
| 3 | other.example.com | False | serve normally | Serve requested content |
| Variable | Start | Request 1 | Request 2 | Request 3 |
|---|---|---|---|---|
| $host | undefined | old.example.com | new.example.com | other.example.com |
| Condition Result | undefined | True | False | False |
Nginx conditional redirect syntax:
if (condition) {
return 301 https://newsite$request_uri;
}
Redirects only if condition is true.
Otherwise, serves request normally.
Use for simple host or path based redirects.if directive do in an nginx configuration for conditional redirects?if in nginxif directive evaluates a condition inside the server or location block.return to redirect users.if checks condition for redirect [OK]if tests, return redirects [OK]if restarts nginxif with loggingif disables server/old to /new using if in nginx?if syntax in nginxreturn directive inside.if [OK]returnserver {
listen 80;
server_name example.com;
location / {
if ($http_user_agent ~* "Mobile") {
return 302 /mobile;
}
}
}http://example.com/?if condition with regex/mobile./mobile with a 302 status. -> Option A/old to /new:if $request_uri = "/old" {
return 301 /new;
}if syntax requirementsif.$request_uri = "/old", causing syntax error.if. -> Option Aif needs parentheses [OK]if conditions in parentheses [OK]ifif/old only if they come from the domain example.com. Which nginx config snippet correctly does this using if?if limitationsif.if for multiple conditionsif blocks allow checking one condition inside another.if correctly; others use unsupported syntax or wrong logic.if for multiple conditions [OK]if for multiple conditions in nginx [OK]ifreturn incorrectlyPass the test and this pattern moves unknown