Create an NGINX Virtual Host

This article explains how to create a simple virtual host configuration to host a website on NGINX. I used Ubuntu 22.04 LTS for this tutorial.

To tell NGINX how to host our website and where it is located, write a server {} context with directives in it:

server {

    listen 80;
    server_name 167.99.93.26;

    root /sites/demo;
  }

server_name: it can contain IP, Domains, and wildcard domains like *.example.com

root: the website files root path

listen: the server listens on port 80

Test and Reload NGINX

nginx -t
sudo systemctl reload nginx

Location Blocks

location {} blocks intercept a request that matches the URI specified and serves content that matches the rules specified within it.

location blocks have 5 ways of URL matching:

  1. Prefix match

  2. Preferential prefix match

  3. Exact match

  4. REGEX match (case sensitive)

  5. REGEX match (case insensitive)

server {

    listen 80;
    server_name 167.99.93.26;

    root /sites/demo;

    # Preferential Prefix match
    location ^~ /Greet2 {
      return 200 'Hello from NGINX "/greet" location.';
    }

    # Exact match
    location = /greet {
      return 200 'Hello from NGINX "/greet" location - EXACT MATCH.';
    }

    # REGEX match - case sensitive
    location ~ /greet[0-9] {
      return 200 'Hello from NGINX "/greet" location - REGEX MATCH.';
    }

    # REGEX match - case insensitive
    location ~* /greet[0-9] {
      return 200 'Hello from NGINX "/greet" location - REGEX MATCH INSENSITIVE.';
    }
  }

Priority of URL matching

  1. Exact match

  2. Preferential prefix match

  3. REGEX match

  4. Prefix match

Preferential prefix match is the same as prefix match, except that it has more priority than regex matches

REGEX matches require the Perl PCRE library. They are used to match URL patterns.

The exact match matches only the specified path, but nothing after it.

The prefix match matches the path and everything after it.

0
Subscribe to my newsletter

Read articles from Melvin C Varghese (melvincv) directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Melvin C Varghese (melvincv)
Melvin C Varghese (melvincv)

I am a DevOps Consultant. 3 years experience with Cloud technologies. 9 years total IT experience in the Linux, Networking and Data Visualization domains. Love listening to music and playing older PC games.