0
0
Nginxdevops~30 mins

Conditional redirects with if in Nginx - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional redirects with if in nginx
📖 Scenario: You are managing a website using nginx web server. You want to redirect users to different pages based on the URL they request.This is common when you want to send visitors from old URLs to new ones or handle special cases.
🎯 Goal: Build an nginx configuration that uses if statements to redirect requests conditionally.You will create a basic server block, add conditions to check the requested URI, and redirect accordingly.
📋 What You'll Learn
Create a server block listening on port 80
Use if statements to check the $request_uri
Redirect /old-page to /new-page
Redirect /special to /special-offer
Use return 301 for permanent redirects
💡 Why This Matters
🌍 Real World
Websites often change URLs or have special pages. Conditional redirects in nginx help send visitors to the right place without broken links.
💼 Career
Knowing how to configure nginx with conditional redirects is a key skill for DevOps engineers and system administrators managing web servers.
Progress0 / 4 steps
1
Create the basic server block
Create a server block that listens on port 80 and has a server_name of example.com. Inside it, add a location / block with a simple root /var/www/html; directive.
Nginx
Need a hint?

Start with server { and add listen 80; and server_name example.com;. Then add location / { root /var/www/html; }.

2
Add first conditional redirect for /old-page
Inside the location / block, add an if statement that checks if $request_uri equals /old-page. If true, use return 301 /new-page; to redirect.
Nginx
Need a hint?

Use if ($request_uri = "/old-page") { return 301 /new-page; } inside the location / block.

3
Add second conditional redirect for /special
Add another if statement inside the location / block that checks if $request_uri equals /special. If true, use return 301 /special-offer; to redirect.
Nginx
Need a hint?

Add a second if block similar to the first, but checking for /special and redirecting to /special-offer.

4
Test and output the final nginx configuration
Print the entire nginx configuration to verify your conditional redirects are set correctly.
Nginx
Need a hint?

Simply output the full nginx configuration you wrote to check it.