Bird
Raised Fist0
Nginxdevops~5 mins

Rewrite directive in Nginx - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes, you want to change the web address a user types into something else behind the scenes. The rewrite directive in nginx helps you do this by changing URLs before the server processes them.
When you want to redirect old website pages to new ones without breaking links.
When you need to remove or add parts of a URL for cleaner addresses.
When you want to force all traffic to use HTTPS instead of HTTP.
When you want to hide query parameters from users by rewriting URLs.
When you want to organize URLs to match your app’s internal structure.
Config File - nginx.conf
nginx.conf
server {
    listen 80;
    server_name example.com www.example.com;

    location = /old-page {
        rewrite ^/old-page$ /new-page permanent;
    }

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}

This configuration listens on port 80 for example.com and www.example.com.

The location = /old-page block uses the rewrite directive to change requests for /old-page to /new-page permanently.

The location / block serves files from the website folder.

Commands
Check the nginx configuration file for syntax errors before applying changes.
Terminal
sudo nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload nginx to apply the new configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
Test the rewrite by requesting the old URL and checking the HTTP headers for a redirect.
Terminal
curl -I http://example.com/old-page
Expected OutputExpected
HTTP/1.1 301 Moved Permanently Server: nginx Location: http://example.com/new-page Content-Type: text/html Content-Length: 178 Connection: keep-alive
Key Concept

If you remember nothing else from this pattern, remember: the rewrite directive changes URLs before nginx processes them, enabling redirects and cleaner URLs.

Common Mistakes
Using rewrite without specifying 'permanent' or 'redirect' flag when a redirect is intended.
Without these flags, nginx rewrites the URL internally but does not tell the browser to change the address, causing confusion.
Add 'permanent' for a 301 redirect or 'redirect' for a 302 redirect to inform the browser.
Not testing nginx configuration with 'nginx -t' before reloading.
Syntax errors can cause nginx to fail to reload, leading to downtime.
Always run 'sudo nginx -t' to verify configuration before reloading.
Placing rewrite directives outside of a location or server block.
Rewrite directives must be inside server or location blocks to work properly.
Put rewrite rules inside the appropriate server or location block.
Summary
Use the rewrite directive inside server or location blocks to change URLs.
Test your nginx configuration with 'nginx -t' before reloading to avoid errors.
Reload nginx with 'systemctl reload nginx' to apply changes without downtime.
Verify rewrites by requesting the old URL and checking for proper redirects.

Practice

(1/5)
1. What is the main purpose of the rewrite directive in nginx?
easy
A. To limit the number of client connections
B. To change URLs based on patterns for redirection or rewriting
C. To configure SSL certificates for secure connections
D. To serve static files directly from the server

Solution

  1. Step 1: Understand the role of rewrite directive

    The rewrite directive is used to modify URLs based on matching patterns.
  2. Step 2: Identify its main use

    It helps redirect or rewrite URLs without changing the visible link to the user.
  3. Final Answer:

    To change URLs based on patterns for redirection or rewriting -> Option B
  4. Quick Check:

    Rewrite directive = URL modification [OK]
Hint: Rewrite changes URLs by pattern matching [OK]
Common Mistakes:
  • Confusing rewrite with serving static files
  • Thinking rewrite manages SSL or security
  • Assuming rewrite limits connections
2. Which of the following is the correct syntax for a rewrite directive in nginx?
easy
A. rewrite ^/oldpath/(.*)$ /newpath/$1 permanent;
B. rewrite /oldpath/(.*) /newpath/$1 redirect
C. rewrite ^/oldpath/(.*)$ /newpath/$1 301
D. rewrite /oldpath/(.*)$ /newpath/$1 permanent

Solution

  1. Step 1: Check the rewrite syntax format

    The correct syntax is: rewrite <pattern> <replacement> <flag>;
  2. Step 2: Identify the correct flag and semicolon usage

    The flag must be a recognized keyword like 'permanent' and the line must end with a semicolon.
  3. Final Answer:

    rewrite ^/oldpath/(.*)$ /newpath/$1 permanent; -> Option A
  4. Quick Check:

    Correct syntax = rewrite + pattern + replacement + flag + semicolon [OK]
Hint: Rewrite ends with semicolon and uses flags like permanent [OK]
Common Mistakes:
  • Omitting the semicolon at the end
  • Using numeric flags instead of keywords
  • Missing caret (^) in regex pattern
3. Given this nginx config snippet:
rewrite ^/blog/(.*)$ /newblog/$1 last;

What happens when a user visits /blog/article1?
medium
A. The user is redirected to /newblog/article1 with a 301 status
B. The URL changes to /newblog/article1 and nginx restarts processing
C. The URL stays /blog/article1 but content from /newblog/article1 is served
D. An error occurs because 'last' is an invalid flag

Solution

  1. Step 1: Understand the 'last' flag in rewrite

    The 'last' flag performs an internal rewrite: nginx changes the URI internally and restarts location processing with the new URI. The browser URL remains unchanged.
  2. Step 2: Apply to the example URL

    Visiting /blog/article1 matches the pattern, rewrites internally to /newblog/article1, and serves content from there without changing the visible URL.
  3. Final Answer:

    The URL stays /blog/article1 but content from /newblog/article1 is served -> Option C
  4. Quick Check:

    'last' flag = internal rewrite, URL unchanged [OK]
Hint: 'last' flag restarts processing with new URL [OK]
Common Mistakes:
  • Confusing 'last' with external redirect
  • Thinking URL visible to user changes
  • Assuming 'last' flag causes error
4. Identify the error in this nginx rewrite directive:
rewrite ^/old/(.*)$ /new/$1 permanent
medium
A. Missing semicolon at the end of the directive
B. Incorrect regex pattern syntax
C. Invalid flag 'permanent' used
D. Rewrite directive cannot use variables like $1

Solution

  1. Step 1: Check syntax completeness

    Every nginx directive must end with a semicolon (;). This line is missing it.
  2. Step 2: Validate other parts

    The regex pattern and flag 'permanent' are correct, and $1 is valid for capturing groups.
  3. Final Answer:

    Missing semicolon at the end of the directive -> Option A
  4. Quick Check:

    Missing semicolon = syntax error [OK]
Hint: Always end rewrite lines with a semicolon [OK]
Common Mistakes:
  • Forgetting semicolon at line end
  • Misunderstanding regex syntax
  • Thinking $1 is invalid in rewrite
5. You want to redirect all requests from /shop/ to /store/ permanently, but only if the URL ends exactly with /shop/ (no extra path after). Which rewrite directive achieves this?
hard
A. rewrite ^/shop/(.*)$ /store/$1 permanent;
B. rewrite ^/shop$ /store/ permanent;
C. rewrite /shop/ /store/ permanent;
D. rewrite ^/shop/$ /store/ permanent;

Solution

  1. Step 1: Match only exact /shop/ URL

    The regex ^/shop/$ matches exactly '/shop/' with nothing after it.
  2. Step 2: Redirect permanently to /store/

    The replacement is /store/ with the 'permanent' flag for 301 redirect.
  3. Final Answer:

    rewrite ^/shop/$ /store/ permanent; -> Option D
  4. Quick Check:

    Exact match with ^/shop/$ and permanent redirect [OK]
Hint: Use ^ and $ to match exact URL in rewrite [OK]
Common Mistakes:
  • Using (.*) which matches extra paths
  • Omitting anchors ^ and $
  • Incorrect regex without end anchor
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard