0
0
Nginxdevops~5 mins

Conditional redirects with if in Nginx - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the if directive do in an nginx configuration?
The if directive checks a condition and executes the code inside its block only if the condition is true. It is often used for conditional redirects or rewrites.
Click to reveal answer
beginner
How do you write a conditional redirect in nginx to send users from http://example.com to https://example.com?
Use the if directive to check if the request is not HTTPS, then use return 301 https://$host$request_uri; to redirect permanently.
Click to reveal answer
intermediate
Why should you avoid complex logic inside nginx if blocks?
Because nginx if is not a full programming language and can cause unexpected behavior or performance issues if used improperly. It's best for simple conditions like redirects.
Click to reveal answer
intermediate
What is the syntax to redirect users to a maintenance page only if the URI contains /old-page?
Use if ($request_uri ~ /old-page) { return 302 /maintenance.html; } inside the server block.
Click to reveal answer
beginner
What HTTP status code is commonly used for permanent redirects in nginx conditional redirects?
The status code 301 is used for permanent redirects, telling browsers and search engines the resource has moved permanently.
Click to reveal answer
Which nginx directive is used to perform conditional redirects?
Alocation
Bmap
Cif
Dproxy_pass
What does this nginx code do? <br>
if ($scheme = http) { return 301 https://$host$request_uri; }
ARedirects HTTP requests to HTTPS
BRedirects HTTPS requests to HTTP
CBlocks HTTP requests
DDoes nothing
Which status code is used for a permanent redirect in nginx?
A200
B404
C500
D301
What is a risk of using complex logic inside nginx if blocks?
AIt can cause unexpected behavior or performance issues
BIt can cause nginx to crash
CIt will always work perfectly
DIt disables logging
How do you redirect requests for /old-page to /maintenance.html using nginx if?
Aif ($request_uri = /old-page) { return 302 /maintenance.html; }
Bif ($request_uri ~ /old-page) { return 302 /maintenance.html; }
Clocation /old-page { return 404; }
Dproxy_pass /maintenance.html;
Explain how to use the nginx if directive to create a conditional redirect from HTTP to HTTPS.
Think about checking the protocol and redirecting to the secure version.
You got /3 concepts.
    Describe best practices and limitations when using if for conditional redirects in nginx.
    Consider performance and reliability when using <code>if</code>.
    You got /4 concepts.