0
0
Nginxdevops~20 mins

Rewrite directive in Nginx - Mini Project: Build & Apply

Choose your learning style9 modes available
Using the Nginx Rewrite Directive
📖 Scenario: You are managing a website hosted on an Nginx server. You want to redirect users from an old URL path to a new one to keep your site organized and avoid broken links.
🎯 Goal: Learn how to use the rewrite directive in Nginx to redirect requests from one URL path to another.
📋 What You'll Learn
Create a server block with a root directory
Add a rewrite rule to redirect from /oldpath to /newpath
Use the correct syntax for the rewrite directive
Test the rewrite by printing the final URL after redirection
💡 Why This Matters
🌍 Real World
Websites often change their URL structure. Using rewrite rules in Nginx helps keep old links working and improves user experience.
💼 Career
Knowing how to configure Nginx rewrite rules is essential for DevOps engineers and system administrators managing web servers.
Progress0 / 4 steps
1
Create a basic Nginx server block
Create a server block with listen 80; and root /var/www/html; inside the http block.
Nginx
Need a hint?

The server block defines how Nginx handles requests. Use listen 80; to listen on port 80 and root /var/www/html; to set the website files location.

2
Add a rewrite rule to redirect /oldpath to /newpath
Inside the server block, add a rewrite directive that matches ^/oldpath$ and redirects to /newpath with a permanent redirect flag permanent.
Nginx
Need a hint?

The rewrite directive uses a regular expression to match the old URL path and redirects permanently to the new path.

3
Add a location block for /newpath
Inside the server block, add a location /newpath block that returns a 200 status with the text New path reached using the return directive.
Nginx
Need a hint?

The location block handles requests to /newpath and returns a simple message to confirm the redirect works.

4
Test the rewrite by simulating a request
Print the final URL after rewriting /oldpath to /newpath by simulating a request in a comment or explanation.
Nginx
Need a hint?

Since Nginx config files do not print output, explain the effect of the rewrite directive in a comment or text.