Hero Image

Configure Nginx Virtual Hosts on Gentoo Linux

Configure Nginx Virtual Hosts on Gentoo Linux

Virtual hosts (server blocks in Nginx terminology) allow a single Nginx instance to serve multiple websites.

Prerequisites

Nginx installed and running. See Install Nginx on Gentoo Linux.

Step 1 – Create the document root

mkdir -p /var/www/example.com/html
chown -R $USER:$USER /var/www/example.com/html
chmod -R 755 /var/www/example.com
echo '<h1>example.com is working</h1>' > /var/www/example.com/html/index.html

Step 2 – Create the server block

Create /etc/nginx/conf.d/example.com.conf:

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

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

    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log;

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

Step 3 – Test and reload

nginx -t
rc-service nginx reload

Step 4 – Verify

curl -H 'Host: example.com' http://localhost

Multiple domains

Repeat Steps 1–3 for each additional domain, changing server_name and root accordingly.