How to create Nginx server blocks (virtual hosts) for different websites?

To create Nginx server blocks (virtual hosts) for different websites, follow these steps:

  1. Navigate to the Nginx configuration directory. This is typically located at /etc/nginx/conf.d/ or /etc/nginx/sites-available/.

  2. Create a new configuration file for your website using a descriptive name. For example, example.com.conf or website.conf. Use the following command to create a new file:

    sudo nano /etc/nginx/conf.d/example.com.conf
  3. Add the following content to the configuration file. Replace example.com with your domain name and the respective server details:

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

    This configuration sets up the server block to listen on port 80 for both IPv4 and IPv6 connections. It specifies the domain name using the server_name directive. It also defines the root directory and the default index files.

  4. Save the changes and exit the editor.

  5. If you're using sites-available and sites-enabled directories, create a symbolic link to enable the site:

    sudo ln -s /etc/nginx/conf.d/example.com.conf /etc/nginx/sites-enabled/

    If you're using a single conf.d directory, skip this step.

  6. Test the configuration to ensure there are no syntax errors:

    sudo nginx -t
  7. If the syntax is correct, restart Nginx to apply the changes:

    sudo systemctl restart nginx

    Now, your Nginx server will handle requests for the specified domain and serve files from the designated root directory.

Repeat these steps for each website or virtual host you want to configure on your Nginx server. Remember to adjust the domain names, file paths, and any other specific settings according to your requirements.