Step-by-Step Guide to Setting Up Server Blocks in Nginx

Configuring server blocks in Nginx is a fundamental skill for anyone venturing into web development or server administration. Server blocks, also known as virtual hosts, allow you to host multiple websites or applications on a single server by directing incoming requests to the appropriate content based on the domain name.


Before diving into the setup process, ensure you have the following prerequisites in place:

  • Nginx Installed: Make sure Nginx is installed on your server. If not, you can install it using your system’s package manager.
  • Domain Names: Have the domain names (or subdomains) ready for the websites you want to host. For the sake of this tutorial, let’s assume you have two domains: and
  • Website Files: Prepare the website files or applications that you intend to serve. These files should be placed in separate directories for each website.

Step 1: Creating Website Directories

Begin by creating directories for each website you plan to host. This ensures clean organization and separation of content. For example, you could create directories named /var/www/example and /var/www/testsite.

Step 2: Setting Up Server Block Configuration Files

Navigate to the Nginx configuration directory (usually /etc/nginx/conf.d/) and create a separate configuration file for each website. Name the files after the domain names, like and

Inside each configuration file, you’ll structure the server block using the following template:

server { listen 80; server_name; root /var/www/example; index index.html; location / { try_files $uri $uri/ =404; } }

Step 3: Adjusting Firewall and DNS Settings

Open port 80, which is the default HTTP port, on your server’s firewall to allow incoming traffic. Also, update the DNS settings for each domain to point to your server’s IP address.

Step 4: Enabling Server Blocks and Testing

Enable the server blocks by creating symbolic links from the configuration files to the sites-enabled directory. Use the ln command for this purpose.

After enabling the server blocks, test the configuration for syntax errors by running:

sudo nginx -t

If everything is fine, reload Nginx to apply the changes:

sudo systemctl reload nginx

Step 5: Viewing Your Websites

Open your web browser and navigate to the domain names you’ve configured. You should now see the content from the respective directories you set up earlier.

In conclusion, setting up server blocks in Nginx allows you to efficiently host multiple websites on a single server, offering a robust solution for web hosting and application deployment. Following this step-by-step guide ensures a smooth configuration process, leading to successful website hosting.

Related Articles