How To Set Up Nginx Server Blocks (Virtual Hosts) on Ubuntu 16.04

How To Set Up Nginx Server Blocks (Virtual Hosts) on Ubuntu 16.04

How To Set Up Nginx Server Blocks (Virtual Hosts) on Ubuntu 16.04

If you're running multiple websites on the same server, you'll need to set up server blocks (virtual hosts) to differentiate them. This tutorial will show you how to set up Nginx server blocks on Ubuntu 16.04.

Step 1: Install Nginx

If you haven't already, install Nginx on your server by running the following command:

sudo apt-get update
sudo apt-get install nginx

Step 2: Create Server Block Directories

Create directories for each server block you want to set up:

sudo mkdir /var/www/example.com
sudo mkdir /var/www/test.com

Step 3: Set Permissions

Set permissions so that Nginx can access the directories:

sudo chown -R $USER:$USER /var/www/example.com
sudo chown -R $USER:$USER /var/www/test.com

Step 4: Create Index Files

Create index files for each website:

echo "This is the default index page for example.com" | sudo tee /var/www/example.com/index.html
echo "This is the default index page for test.com" | sudo tee /var/www/test.com/index.html

Step 5: Create Server Block Configuration Files

Create server block configuration files for each website:

sudo nano /etc/nginx/sites-available/example.com
sudo nano /etc/nginx/sites-available/test.com

For example.com, add the following configuration:

server {
    listen 80;
    listen [::]:80;

    root /var/www/example.com;
    index index.html;

    server_name example.com www.example.com;

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

For test.com, add the following configuration:

server {
    listen 80;
    listen [::]:80;

    root /var/www/test.com;
    index index.html;

    server_name test.com www.test.com;

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

Step 6: Enable Server Blocks

Create symbolic links from the server block configuration files to the sites-enabled directory:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/sites-available/test.com /etc/nginx/sites-enabled/

Step 7: Test Configuration and Restart Nginx

Test the Nginx configuration and restart Nginx:

sudo nginx -t
sudo systemctl restart nginx

That's it! You

Комментарии

Популярные сообщения из этого блога

How To Modify CSS Classes in JavaScript

How To Backup MySQL Databases on an Ubuntu VPS

How To Backup PostgreSQL Databases on an Ubuntu VPS