Technology Encyclopedia Home >How to configure virtual hosts and domain names on an HTTP server?

How to configure virtual hosts and domain names on an HTTP server?

Configuring virtual hosts and domain names on an HTTP server allows you to host multiple websites on a single server, each with its own domain name. This is achieved by setting up virtual hosts in your web server configuration.

For example, if you are using Apache HTTP Server, you can configure virtual hosts by editing the httpd.conf file or by creating separate configuration files for each virtual host in the sites-available directory (on Debian-based systems) or conf.d directory (on Red Hat-based systems).

Here is a basic example of how to set up a virtual host in Apache:

  1. Create a new configuration file for your virtual host, e.g., example.com.conf.
  2. Add the following configuration to the file:
<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    DocumentRoot /var/www/example.com/public_html
    ServerName example.com
    ServerAlias www.example.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

In this example:

  • ServerAdmin specifies the email address of the server administrator.
  • DocumentRoot is the directory where your website files are stored.
  • ServerName is the primary domain name for the virtual host.
  • ServerAlias allows you to specify additional domain names that should be treated as aliases for the primary domain.
  • ErrorLog and CustomLog specify the locations of the error and access logs, respectively.

After creating the configuration file, you need to enable the virtual host and restart Apache:

sudo a2ensite example.com.conf
sudo systemctl restart apache2

For Nginx, the configuration would look something like this:

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/public_html;
    index index.html index.htm;

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

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

After configuring Nginx, you would test the configuration and then reload Nginx:

sudo nginx -t
sudo systemctl reload nginx

If you are hosting your website on a cloud platform like Tencent Cloud, you can use services like Tencent Cloud Virtual Private Cloud (VPC) and Cloud Load Balancer to manage your virtual hosts and domain names more efficiently. These services provide additional features such as load balancing, security groups, and high availability configurations.