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.