Learn Nginx · 3/13

Serving Static Web Content

7 min read

Serving Static Web Content with Nginx nginx

Welcome back to the freeCodeCamp guide on Nginx! Today, we're diving into the bread and butter of web servers: serving static content. That's your HTML, CSS, JavaScript files, images, and all the other assets that make up a website.

Let's get started!


1. Setting up a Basic Web Server for HTML/CSS/JS 🖥️

The Problem: You've built a beautiful website with HTML, CSS, and JavaScript on your local machine. Now, you want to share it with the world. How do you get it from your computer onto the internet for everyone to see?

The Solution: You need a web server! A web server is a piece of software that listens for incoming requests from browsers and, in this case, sends back your website's files. Nginx is a fantastic, high-performance web server that can do this for you.

What's Happening Under the Hood?

When you type a URL like http://example.com into your browser, your browser sends an HTTP request to the server at example.com. Nginx, running on that server, catches this request. It then looks at its configuration to figure out what to do. For a simple static site, it will find the requested file on the server's filesystem and send it back to your browser. Your browser then renders the HTML, CSS, and JavaScript to display the webpage. It's like a super-fast librarian fetching the exact book you asked for.

Let's Get Our Hands Dirty: A Basic Nginx Configuration

Here’s a simple Nginx configuration to serve a static website. We'll break it down piece by piece.

nginx
server {
    listen 80;
    server_name your_domain.com www.your_domain.com;

    root /var/www/your_domain;

    index index.html;

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

Breaking it down:

  • listen 80;: This tells Nginx to listen for incoming connections on port 80, which is the standard port for HTTP traffic.
  • server_name your_domain.com www.your_domain.com;: This specifies which domain names this server block should respond to.
  • root /var/www/your_domain;: This is the most important directive for serving static files. It tells Nginx the root directory where your website's files are located on the server. When a request comes in for http://your_domain.com/about.html, Nginx will look for a file at /var/www/your_domain/about.html.
  • index index.html;: This directive tells Nginx which file to serve if the user requests a directory. So, if someone visits http://your_domain.com/, Nginx will look for and serve /var/www/your_domain/index.html.
  • location / { ... }: This is a location block. The / means it will match any request for your site.
  • try_files $uri $uri/ =404;: This is a powerful directive. It tells Nginx to first look for a file with the exact name requested ($uri). If it doesn't find a file, it then looks for a directory with that name ($uri/). If neither is found, it will return a 404 Not Found error.

Industry Practice: It's a standard convention to place your website's files in the /var/www/ directory on your server. Each site should have its own subdirectory, like /var/www/your_domain.


2. The Great Debate: Understanding 'root' vs. 'alias' 🤔

The Problem: You want to serve files from a directory, but you don't want the directory itself to be part of the URL. Or maybe you want to organize your files in a certain way on the server that doesn't exactly match your website's URL structure.

The Solution: Nginx gives you two directives to handle this: root and alias. Understanding the difference is crucial for a clean configuration.

  • root: Appends the URI to the path.
  • alias: Replaces the location with the path.

Let's see this in action.

The root Directive

As we saw earlier, root defines the base directory for the entire server or a specific location.

Example:

nginx
location /images/ {
    root /var/www/data;
}

If a request comes in for /images/logo.png, Nginx will look for the file at /var/www/data/images/logo.png. Notice how the /images/ part of the request is appended to the root path.

The alias Directive

alias is a bit different. It defines a replacement for the location part of the request.

Example:

nginx
location /images/ {
    alias /var/www/data/images/;
}

If a request comes in for /images/logo.png, Nginx will look for the file at /var/www/data/images/logo.png. In this specific case, it seems to do the same thing as root, right?

Here's the key difference:

Let's change the alias path:

nginx
location /images/ {
    alias /var/www/assets/;
}

Now, a request for /images/logo.png will be served from /var/www/assets/logo.png. See how /images/ was replaced by /var/www/assets/?

When to use which?

  • Use root in your main server block and for most location blocks. It's generally more straightforward.
  • Use alias when you want to serve content from a directory that has a different name than the location block. This is useful for organizing files on your server without affecting the URLs.

A funny exaggeration: Using alias incorrectly is like telling a delivery driver to go to "123 Main Street," but when they get there, you've secretly renamed the street to "456 Side Avenue" without telling them. They'll be lost and confused, just like Nginx will be if your paths are wrong!


3. Configuring Index Files and Autoindex (Directory Listings) 📂

The Problem: What happens when a user navigates to a directory in their browser, like http://your_domain.com/blog/? Should they see a specific page, or should they see a list of all the files in that directory?

The Solution: Nginx provides the index and autoindex directives to control this behavior.

The index Directive

We've already seen index in action. It tells Nginx what file to serve when a directory is requested. You can even specify multiple files in order of preference.

Example:

nginx
index index.html index.htm default.html;

With this configuration, if a user requests /, Nginx will first look for index.html. If that's not found, it will look for index.htm, and if that's not found, it will look for default.html.

The autoindex Directive

Sometimes, you might want to show a list of files in a directory. This can be useful for things like file downloads or simple archives. This is where autoindex comes in.

Example:

nginx
location /downloads/ {
    autoindex on;
}

Now, if a user goes to http://your_domain.com/downloads/, and there's no index.html file in that directory, Nginx will generate a simple HTML page listing all the files and subdirectories.

Fun Fact: autoindex is a bit of a throwback to the early days of the web, where you'd often see simple, unstyled directory listings. While not always pretty, it can be incredibly useful for internal tools or public file shares.

Industry Practice: For public-facing websites, it's generally best to have an index file for every directory to provide a good user experience. autoindex is more commonly used for specific, intentional purposes.


4. Graceful Failures: Handling Custom Error Pages (404, 50x) 😢

The Problem: Sooner or later, a user will try to visit a page that doesn't exist (404 Not Found), or your server might encounter an internal error (50x errors like 500 Internal Server Error). By default, Nginx shows a very plain, unhelpful error page. This can be jarring for users and doesn't reflect your site's branding.

The Solution: Nginx makes it easy to create and serve your own custom error pages.

The error_page Directive

The error_page directive lets you specify a custom page to be shown for one or more HTTP error codes.

Example:

nginx
server {
    # ... other directives ...

    error_page 404 /404.html;

    location = /404.html {
        internal;
    }

    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        internal;
    }
}

Let's break this down:

  • error_page 404 /404.html;: This tells Nginx that whenever a 404 Not Found error occurs, it should do an internal redirect to /404.html.
  • location = /404.html { internal; }: This is the clever part.
    • location = /404.html: This creates a specific location block that only matches the exact URI /404.html.
    • internal;: This directive makes this location only accessible through internal Nginx redirects. A user cannot directly visit http://your_domain.com/404.html. This prevents your error page from being indexed by search engines or appearing in your site's analytics as a regular page.
  • error_page 500 502 503 504 /50x.html;: You can also group multiple error codes to a single custom error page. This is great for server-side errors.

Why is this important?

A good custom error page can:

  • Keep your site's look and feel consistent.
  • Provide helpful information to the user, like a link back to the homepage or a search bar.
  • Have a bit of fun! A creative 404 page can be a memorable part of your website.

Further Reading 📚

Challenge

You are tasked with creating a complete Nginx configuration for a static website called pixelperfect.dev. The configuration must be contained within a single server block and meet the following specific requirements:

  1. The server must listen for HTTP requests on port 80.
  2. The server name should be pixelperfect.dev.
  3. The main document root for the website is located at /var/www/pixelperfect/public.
  4. When a user requests a directory, Nginx should first try to serve home.html and then index.html.
  5. Requests for URLs starting with /assets/images/ must be served from the filesystem directory /srv/cdn/images/. For example, a request for /assets/images/logo.png should resolve to the file /srv/cdn/images/logo.png.
  6. Requests for a special directory at /downloads/ should display an auto-generated directory listing if no index file is found.
  7. Any 404 Not Found error must trigger an internal redirect to serve the custom page /error_404.html. This error page must not be directly accessible by users.
  8. All server-side errors (500, 502, 503, 504) must trigger an internal redirect to a single custom page, /error_50x.html, which also must not be directly accessible by users.

Expected result

Your solution should be a single, complete Nginx server block. The configuration should correctly use the listen, server_name, root, and index directives at the server level. It must contain distinct location blocks to handle different URL paths:

  • A location block for /assets/images/ that uses the alias directive to map to the /srv/cdn/images/ directory.
  • A location block for /downloads/ with autoindex on;.
  • Two location blocks for /error_404.html and /error_50x.html, both marked as internal.

The error_page directive should be used twice: once to map the 404 code to /error_404.html, and once to map the codes 500, 502, 503, and 504 to /error_50x.html.

nginx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.