Nginx Server Block to create a virtual host

Introduction

A brief overview of Nginx:
Nginx (pronounced as “engine-x”) is a high-performance HTTP server, reverse proxy and IMAP/POP3 proxy server. Since its inception in 2002, it has become one of the most popular web servers in the world, known for its scalability, robustness, and rich feature set.

What is a server block?
In the Nginx world, a server block is analogous to virtual hosts in Apache. It allows you to define how to respond to requests for different domains or IP addresses on a single machine. In essence, server blocks can be likened to virtual web hosting setups where a single web server serves multiple websites.

Why use server blocks for virtual hosting?
Server blocks empower administrators to:

  • Host multiple websites on a single server.
  • Define custom settings for each site, such as security configurations, log files and SSL setups.
  • Efficiently manage and organize domain-specific configurations.

Prerequisites

Hardware and Software Requirements:
While the specific requirements might vary based on the traffic and resources each site demands, a general setup would include:

  • A server running a Linux distribution.
  • Sufficient RAM and storage based on anticipated web traffic.

Ensuring Nginx is installed and running:
Before proceeding, make sure that Nginx is installed on your server. You can check its status using the following commands:

sudo systemctl status nginx

If not installed, you can typically install it using package management tools like apt or yum depending on your Linux distribution.

Access Privileges Needed:
Ensure you have root or sudo privileges. This is essential for editing configuration files, restarting the server, and creating directories. Most operations related to server blocks require elevated permissions.

Understanding the Default Server Block

A look at the default configuration:
When you first install Nginx, it comes with a default server block configuration. This configuration is usually found at /etc/nginx/sites-available/default or /etc/nginx/conf.d/default.conf based on your installation. This file serves as both a template and a fallback for server requests that don’t match any other defined server block.

Significance of the default server block:
The default configuration is invaluable for several reasons:

  • Fallback Mechanism: If no server block matches the incoming request, the default block is used. This can help prevent unwanted exposures of hosted sites that might not have a matching server block yet.
  • Template: For those new to Nginx, the default configuration acts as a teaching aid, showcasing the basic structure and directives of a typical server block.
  • Troubleshooting: By comparing custom server blocks with the default, one can troubleshoot configuration issues or mistakes that might arise.

How can we add multiple hosts to Nginx?

You can host multiple websites on a single machine using Nginx Server Block. You need to add a separate “Server Block” for each website in the Nginx configuration section.

How to Add a Server Block

Please create a server block into this path sudo vi /etc/nginx/conf.d/sameple.com.conf

server {
    listen 80;
    server_name u.awswithatiq.com; 

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

To create a Virtual Server Block for PHP-FPM then add this code in the /etc/nginx/conf.d/sameple.com.conf file

server {
    listen 80;
    server_name www.gcptips.com;
    rewrite ^ $scheme://gcptips.com$request_uri?;
}

server {
    listen 80;
    server_name gcptips.com;
    
    root /var/www/wordpress;
    index index.php;
    charset UTF-8;
    
    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ \.php$ {
        try_files $uri =404;

        include fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_index index.php;
        # fastcgi_intercept_errors on;
        # fastcgi_keep_conn on;
        # fastcgi_read_timeout 300;

        # fastcgi_pass   127.0.0.1:9000;
        fastcgi_pass  unix:/var/run/php-fpm/www.sock;
        #for ubuntu unix:/var/run/php/php8.0-fpm.sock;

        ##
        # FastCGI cache config
        ##

        # fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=WORDPRESS:10m max_size=1000m inactive=60m;
        # fastcgi_cache_key $scheme$host$request_uri$request_method;
        # fastcgi_cache_use_stale updating error timeout invalid_header http_500;        
        
        fastcgi_cache_valid any 30m;
    }
}

To enable Gzip compression please use these lines under the server block

# Enable Gzip
  gzip  on;
  gzip_http_version 1.0;
  gzip_comp_level 2;
  gzip_min_length 1100;
  gzip_buffers     4 8k;
  gzip_proxied any;
  gzip_types
    # text/html is always compressed by HttpGzipModule
    text/css
    text/javascript
    text/xml
    text/plain
    text/x-component
    application/javascript
    application/json
    application/xml
    application/rss+xml
    font/truetype
    font/opentype
    application/vnd.ms-fontobject
    image/svg+xml;

  gzip_static on;

  gzip_proxied        expired no-cache no-store private auth;
  gzip_disable        "MSIE [1-6]\.";
  gzip_vary           on;

Add expires by adding the following lines in your code

. . .
# Default server configuration
#

# Expires map
map $sent_http_content_type $expires {
    default                    off;
    text/html                  epoch;
    text/css                   max;
    application/javascript     max;
    ~image/                    max;
}

server {
    listen 80 gcptips.com;
    listen [::]:80 gcptips.com;

    expires $expires;

For WordPress URL rewrite, please add the following lines inside the server block

location / {
                             
                try_files $uri $uri/ /index.php?$args;
        }

Testing Configuration Syntax

Before applying changes, it’s crucial to validate the syntax of your configuration files. Even a small oversight can prevent Nginx from starting or operating correctly.

Using the nginx -t command:
This command checks your configuration files for syntax validity without restarting the service.

sudo nginx -t

If you encounter any errors, the output will provide clues about the location and nature of the problem. Correct any issues before proceeding.

Troubleshooting common syntax errors:
Here are a few common culprits:

  • Missing semicolons at the end of directives.
  • Mismatched curly braces { }.
  • Directives placed in the wrong context (e.g., an HTTP directive inside a server block).
  • Typos or misspellings.

Always refer to the error message, as it will usually indicate the line number where the problem resides.

To check the error log, please run this command

sudo tail -30 /var/log/nginx/error.log

A detailed explanation is given here.

Common Pitfalls and Solutions

Even seasoned administrators can sometimes encounter challenges. Here are a few pitfalls to be aware of:

1. 403 Forbidden:
Often due to the directory or file permissions. Ensure that Nginx (or the user it runs as, often www-data or nginx) has the appropriate permissions to read from the web directory.

2. 404 Not Found:
Usually indicates that the requested file or resource isn’t in the specified root directory. Double-check file paths and spellings.

3. 502 Bad Gateway:
This typically occurs when Nginx can’t communicate with a proxied service, like a PHP-FPM process. Verify that all backend services are running.

Conclusion

Nginx’s flexibility as a web server shines most brightly when managing multiple websites through virtual hosts or server blocks. While the setup process requires attention to detail, the ability to host, customize, and secure multiple sites on a single server offers immense value. As with all web administration tasks, regular monitoring, updates, and backups are crucial to maintaining a secure and efficient server environment.

Frequently Asked Questions (FAQ)

1. Can I host multiple domains with one server block?
Yes, by specifying multiple domains in the server_name directive, like server_name example1.com example2.com;. However, it’s advisable to separate domains if they have distinct content or configurations.

2. How do I renew my Let’s Encrypt certificates?
Certbot can automate this. You can manually renew with sudo certbot renew or set up a cron job for automatic renewal.

3. Why is my new configuration not taking effect after reloading Nginx?
Ensure you’ve created a symbolic link to the sites-enabled directory and that there are no configuration errors. Also, double-check the domain DNS settings.

4. How can I prioritize one server block over another?
Nginx evaluates server blocks in the order they appear. If multiple blocks match, the first one is used. Organize your configuration files keeping this in mind.

Atiqur Rahman

I am MD. Atiqur Rahman graduated from BUET and is an AWS-certified solutions architect. I have successfully achieved 6 certifications from AWS including Cloud Practitioner, Solutions Architect, SysOps Administrator, and Developer Associate. I have more than 8 years of working experience as a DevOps engineer designing complex SAAS applications.

This Post Has 3 Comments

Leave a Reply