Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 30 ยท Practice and Review

Practice: Configuration Exercises with Solutions

Twelve graded Nginx and Apache configuration exercises with solutions: locations, redirect loops, vhost choice, proxy_pass slashes, alias traps, limits and more.

Reading about configuration is not the same as writing it. Web server configuration has a handful of sharp edges (a missing slash, a rule that matches earlier than you expected, a header that is silently dropped), and you only remember them after you have cut yourself once or twice. These twelve exercises let you do that safely, on paper.

They are graded from easy to hard. Try each one before you open its solution: write the directives, or predict the outcome, and only then compare. Some exercises come with a stand-in checker, a small JavaScript program that applies the same rules as the real servers, so you can test your prediction. The checkers reproduce the rules; they are not nginx or Apache, and all real configuration here is read-only.

How to use this page

Write first Draft your answer before reading the solution.
Run the checker Test predictions with the JavaScript stand-ins.
Explain why A right answer you cannot explain is luck.

Twelve tasks, three levels, one habit.

1 / 2

Level 1: warm-up

Exercise 1: a static site

Write an nginx server block for example.com and www.example.com. Files live in /var/www/example, the index is index.html, and a missing page must show /var/www/example/404.html.

Solution

NGINX
server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example;
    index index.html;
    error_page 404 /404.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

root is set at server level so every location inherits it. try_files checks the file, then the directory (which uses index), and answers 404 otherwise; error_page turns that 404 into your custom page. See Server Blocks and Choosing a Server if any line is unclear.

Exercise 2: one canonical host

Visitors should always end up on https://example.com, whether they type www.example.com or use plain HTTP. Write the redirect in nginx and in Apache. Use a permanent redirect and keep the path.

Solution (nginx)

NGINX
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    server_name www.example.com;
    # ssl_certificate lines omitted
    return 301 https://example.com$request_uri;
}

Solution (Apache)

APACHE
<VirtualHost *:80>
    ServerName example.com
    ServerAlias www.example.com
    Redirect permanent / https://example.com/
</VirtualHost>

<VirtualHost *:443>
    ServerName www.example.com
    # SSL lines omitted
    Redirect permanent / https://example.com/
</VirtualHost>

Both use a plain return or Redirect, which is faster and clearer than a regular-expression rewrite. Redirect keeps the rest of the path automatically, while nginx needs $request_uri (path and query string). The www HTTPS site needs a certificate, even though it only redirects, because the TLS handshake happens before the redirect is sent.

Exercise 3: which server block answers?

A server has four blocks: A for example.com and www.example.com, B for *.example.com, C for the regex ~^shop\d+\.example\.net$, and D marked default_server. Predict the block that answers each of these Host values: www.example.com, blog.example.com, shop7.example.net, other.org. Then run the first half of the checker below.

Exercise 4: which location wins?

The site has five locations: /, /images/, ^~ /static/, ~* \.(png|jpg)$ and = /health. Predict which one handles /health, /images/cat.PNG, /static/logo.png, /about and /images/readme.txt. The surprise is usually the second and third.

JS Checker: server blocks and locations

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions. For exercise 3: www.example.com goes to A (an exact name beats a wildcard), blog.example.com to B, shop7.example.net to C (no exact or wildcard match, so the first matching regex wins), and other.org to D because it is the default. For exercise 4: /health hits the exact location; /images/cat.PNG goes to the regex (L4, case-insensitive) even though /images/ is the longest prefix, because after finding the best prefix nginx tests the regular expressions and a regex match overrides an ordinary prefix; /static/logo.png stays with ^~ because that modifier cancels the regex search; /about falls to /, and /images/readme.txt stays with /images/ because no regex matches. The full rules are in Location Blocks and Matching Order.

Level 2: common bugs

Exercise 5: the API returns 404 behind the proxy

The backend has routes like /users. This config sends /api/users to http://127.0.0.1:3000/api/users, which does not exist. Fix it so the backend receives /users.

NGINX
location /api/ {
    proxy_pass http://127.0.0.1:3000;
}

Solution. Add the URI part (a trailing slash) to proxy_pass:

NGINX
location /api/ {
    proxy_pass http://127.0.0.1:3000/;
}

Without a URI in proxy_pass, nginx forwards the original path. With one, the matched prefix is replaced by it.

Exercise 6: ERR_TOO_MANY_REDIRECTS

A site sits behind a proxy that terminates TLS and talks plain HTTP to the application. The application contains "if the request is not HTTPS, redirect to HTTPS". Visitors on https:// get an endless redirect loop. Why, and what are two fixes?

Solution. The application only ever sees plain HTTP from the proxy, so it believes every request is insecure and redirects each one, forever. Fix A: make the application honor X-Forwarded-Proto (frameworks call this "trusted proxies"), with the proxy sending proxy_set_header X-Forwarded-Proto $scheme;. Fix B: delete the redirect from the application and do it only at the edge, in the port 80 server block. A second classic loop is two rules that undo each other, such as "add a trailing slash" plus "remove a trailing slash". The checker below follows redirects and reports both kinds.

Exercise 7: the alias trap

This location should serve /static/app.css from /var/www/assets/app.css, but the server looks for /var/www/assetsapp.css. Fix it, and say how root would behave instead.

NGINX
location /static/ {
    alias /var/www/assets;
}

Solution. alias replaces the matched part of the URL with its value, so the rest (app.css) is simply appended. The alias must therefore end with a slash when the location does:

NGINX
location /static/ {
    alias /var/www/assets/;
}

With root /var/www; inside the same location, nginx would append the whole URL and look for /var/www/static/app.css.

JS Checker: proxy_pass, alias and root paths

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Checker: find the redirect loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 8: tune a rate limit

The login endpoint /login must allow about 5 attempts per minute per IP address, tolerating a short burst of 3 extra attempts, and rejected requests should get status 429. Write the two nginx pieces.

Solution

NGINX
# http level
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
limit_req_status 429;

# inside the server block
location = /login {
    limit_req zone=login burst=3 nodelay;
    proxy_pass http://app_pool;
}

$binary_remote_addr is a compact form of the client address, so one megabyte of zone memory holds roughly sixteen thousand addresses and the 10 MB zone is plenty. rate=5r/m is per minute, and burst=3 with nodelay serves up to four attempts at once before rejecting. Behind a CDN or proxy, $remote_addr is the proxy's address, so everyone would share one bucket: restore the real client IP first (see Reverse Proxy Basics).

Level 3: Apache and operations

Exercise 9: .htaccess rules are ignored

You put RewriteRule lines in /var/www/site/.htaccess, and nothing happens. Give two causes and the fix.

Solution. The usual cause is AllowOverride None for that directory, so Apache never reads the file. Others: mod_rewrite is not loaded (a2enmod rewrite) or the file lacks RewriteEngine On. The fix for the first is to allow what the file needs:

APACHE
<Directory /var/www/site>
    AllowOverride FileInfo
    Require all granted
</Directory>

Better still, move the rules into the <Directory> block (or the vhost) and keep AllowOverride None: the main configuration is read once at startup, while .htaccess files are searched for on every request. See .htaccess, Directory Rules and AllowOverride.

Exercise 10: WebSockets fail or die after a minute

A chat app works locally, but through nginx the connection fails with an error during the handshake, or connects and then drops after 60 seconds of silence. Fix the proxy block.

Solution

NGINX
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

location /socket/ {
    proxy_pass http://127.0.0.1:3001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade    $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_read_timeout 3600s;
}

Upgrade and Connection are hop-by-hop headers that nginx does not pass on by itself, and nginx speaks HTTP/1.0 to backends unless told otherwise. The silent drop at 60 seconds is the default proxy_read_timeout: the app should also send periodic ping frames.

Exercise 11: uploads return 413

Users cannot upload a 30 MB video. Nginx answers 413 Request Entity Too Large. Name every setting you must check for a PHP application behind nginx and give the values for a 50 MB limit.

Solution. Three limits, in this order: nginx client_max_body_size 50m; (default 1m), PHP post_max_size = 52M and PHP upload_max_filesize = 50M. The web server's value comes first and post_max_size is a little larger than the file limit to leave room for other form fields. Remember to reload both nginx and PHP-FPM. Apache's matching directive is LimitRequestBody 52428800.

Exercise 12: 502 or 504?

Read these two error log lines and say what each means and what you would do.

TEXT
connect() failed (111: Connection refused) while connecting to upstream, upstream: "http://127.0.0.1:3000/"
upstream timed out (110: Connection timed out) while reading response header from upstream

Solution. The first is a 502: nothing is listening on port 3000, so the application crashed, was never started or listens on another port or socket. Check the service (systemctl status), the port (ss -ltnp) and the proxy_pass address. The second is a 504: the connection worked, but the application did not answer within proxy_read_timeout. Look for a slow query or a hung worker first; raise the timeout only for routes that are legitimately slow. Logs and Troubleshooting covers this diagnosis in depth.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In nginx, a request matches the prefix location /images/ and the regex location ~* .png$. Which one handles it?

    Regex locations override plain prefix locations when they match. Only ^~ on the best prefix, or an exact = match, stops the regex search.
  2. 2. You change alias /var/www/assets; for location /static/ and the files are not found: the server looks in /var/www/assetsapp.css. What is wrong?

    alias substitutes the matched prefix with its value and appends the rest of the URL, so the slashes of location and alias must agree.
  3. 3. A page behind a TLS-terminating proxy loops forever on 'redirect to HTTPS'. What is the most likely cause?

    The app cannot know the client used HTTPS unless the proxy tells it, so it redirects every request.
  4. 4. An error log line says 'upstream timed out ... while reading response header'. Which status does the client get?

    The proxy reached the backend but gave up waiting for its answer, which is a gateway timeout. 502 is for refused or broken connections.

Summary

  • Server choice goes: exact name, wildcard, regex, default; location choice goes: exact, longest prefix (^~ stops there), regex, prefix.
  • A trailing slash decides whether proxy_pass strips the prefix, and whether alias joins paths correctly.
  • Redirect loops come from an app that cannot see the real scheme, or from rules that undo each other.
  • Rate limits need a rate, a burst and a status; behind proxies, fix the client IP first.
  • Upload problems are a chain of three limits; WebSocket problems are missing headers or the default 60-second timeout.
  • 502 means the backend connection failed, 504 means it was too slow.

Next: Interview Questions.