0
0
Nginxdevops~30 mins

Trailing slash normalization in Nginx - Mini Project: Build & Apply

Choose your learning style9 modes available
Trailing Slash Normalization in nginx
📖 Scenario: You are managing a website using nginx as the web server. Sometimes users visit URLs with or without a trailing slash (like /about or /about/), which can cause duplicate content or broken links. To keep URLs consistent and improve SEO, you want to make sure all URLs end with a trailing slash.
🎯 Goal: Configure nginx to automatically add a trailing slash to URLs that don't have one, except for requests to files (like image.png) or the root URL.
📋 What You'll Learn
Create a server block with a root location
Add a variable to check if the URL ends with a slash
Write a rewrite rule to add a trailing slash if missing
Test the configuration by printing the final rewritten URL
💡 Why This Matters
🌍 Real World
Websites often have inconsistent URLs with or without trailing slashes. Normalizing URLs improves user experience and search engine ranking.
💼 Career
DevOps engineers and site reliability engineers frequently configure web servers like nginx to handle URL normalization and redirects for production websites.
Progress0 / 4 steps
1
Create the basic nginx server block
Write an nginx server block with listen 80; and server_name example.com;. Inside it, create a location / block with root /var/www/html;.
Nginx
Need a hint?

Start by defining a server block listening on port 80 for example.com. Then add a location block for the root path with the root directory.

2
Add a variable to check for trailing slash
Inside the location / block, add a variable $has_trailing_slash that is 1 if the request URI ends with a slash, otherwise 0. Use the set directive and if condition with $request_uri.
Nginx
Need a hint?

Use set to create the variable and an if block with a regex to check if $request_uri ends with a slash.

3
Add rewrite rule to append trailing slash
Inside the location / block, add an if condition that checks if $has_trailing_slash is 0 and the URI does not contain a dot (to exclude files). If true, use rewrite to redirect to the same URI with a trailing slash and a 301 status.
Nginx
Need a hint?

Use nested if blocks to check both conditions, then use rewrite with permanent to redirect.

4
Print the final rewritten URL for testing
Add a return 200 directive inside the location / block that returns the current URI with a trailing slash if it was added, or the original URI otherwise. Use return 200 "$request_uri"; to display the URI.
Nginx
Need a hint?

Use return 200 "$request_uri"; to output the current URI for testing purposes.