How to configure Nginx to serve multiple websites on the same server?

To configure Nginx to serve multiple websites on the same server, you can follow these steps:

  1. Install Nginx:

    • On Ubuntu or Debian: sudo apt update && sudo apt install nginx
    • On CentOS or Fedora: sudo yum install nginx
  2. Create directories for each website:

    • sudo mkdir -p /var/www/website1
    • sudo mkdir -p /var/www/website2
  3. Assign ownership of the directories to the web server user:

    • sudo chown -R www-data:www-data /var/www/website1
    • sudo chown -R www-data:www-data /var/www/website2
  4. Create Nginx server blocks:

    • sudo nano /etc/nginx/sites-available/website1

    • Add the following configuration (replace example.com with your domain name and /var/www/website1 with the correct path):

      server { listen 80; server_name website1.com www.website1.com; root /var/www/website1; location / { try_files $uri $uri/ =404; } }
    • sudo nano /etc/nginx/sites-available/website2

    • Add the following configuration (replace example.com with your domain name and /var/www/website2 with the correct path):

      server { listen 80; server_name website2.com www.website2.com; root /var/www/website2; location / { try_files $uri $uri/ =404; } }
  5. Link the server block configuration files:

    • sudo ln -s /etc/nginx/sites-available/website1 /etc/nginx/sites-enabled/
    • sudo ln -s /etc/nginx/sites-available/website2 /etc/nginx/sites-enabled/
  6. Test the Nginx configuration:

    • sudo nginx -t
  7. If the test is successful, reload Nginx to apply the changes:

    • sudo systemctl reload nginx
  8. Ensure your domain names point to the correct IP address of your server.

By following these steps, you should have Nginx configured to serve multiple websites on the same server.