0
0
Nginxdevops~30 mins

Named locations (@) in Nginx - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Named Locations (@) in Nginx Configuration
📖 Scenario: You are setting up a simple Nginx web server. You want to handle requests differently based on the URL path. Sometimes, you want to redirect users to a special internal page without exposing the URL change.
🎯 Goal: Build an Nginx configuration that uses named locations (starting with @) to internally redirect requests to a custom error page.
📋 What You'll Learn
Create a server block listening on port 80
Define a location / that checks if a file exists
If the file does not exist, internally redirect to a named location @custom_404
Define the named location @custom_404 to serve a custom 404 error page
Print the final Nginx configuration
💡 Why This Matters
🌍 Real World
Named locations in Nginx help redirect requests internally without changing the URL seen by users. This is useful for custom error handling, maintenance pages, or complex routing.
💼 Career
Understanding named locations is important for DevOps roles managing web servers, enabling better control over request handling and improving user experience with custom error pages.
Progress0 / 4 steps
1
Create the basic server block
Create an Nginx server block listening on port 80 with a root directory set to /var/www/html.
Nginx
Need a hint?

Use listen 80; to listen on port 80 and root /var/www/html; to set the root directory.

2
Add location / with try_files and named location redirect
Inside the server block, add a location / block that uses try_files $uri $uri/ @custom_404; to check if the requested file or directory exists, and if not, redirect internally to the named location @custom_404.
Nginx
Need a hint?

The try_files directive tries the listed files or directories, and if none exist, it redirects internally to the named location.

3
Define the named location @custom_404
Add a named location @custom_404 inside the server block that returns a 404 status and serves the file /var/www/html/custom_404.html using internal and root directives.
Nginx
Need a hint?

The internal directive makes the named location accessible only by internal redirects, not by direct client requests.

4
Print the complete Nginx configuration
Print the entire Nginx configuration you have created so far.
Nginx
Need a hint?

Use a print statement to output the full configuration text exactly as written.