Dump the code

Configuring virtual hosts

Created 9 months ago
Posted By admin
3min read
Configuring virtual hosts, also known as server blocks in Nginx, allows you to host multiple websites or applications on the same server. Each virtual host has its own configuration, allowing you to define separate settings for different domains or subdomains. Here's a step-by-step guide on configuring virtual hosts in Nginx:

1. Create configuration files:

Nginx typically has a main configuration file (e.g., /etc/nginx/nginx.conf) and a directory for additional configuration files (e.g., /etc/nginx/conf.d/). In the latter directory, you can create separate configuration files for each virtual host.

sudo nano /etc/nginx/conf.d/example1.conf
sudo nano /etc/nginx/conf.d/example2.conf

2. Define server blocks:

Inside each configuration file, define server blocks for each virtual host. Here's an example for two virtual hosts:

- example1.conf

server {
    listen 80;
    server_name www.example1.com example1.com;

    root /path/to/example1;
    index index.html;

    location / {
        # Additional configuration for the first virtual host
    }
}

- example2.conf

server {
    listen 80;
    server_name www.example2.com example2.com;

    root /path/to/example2;
    index index.html;

    location / {
        # Additional configuration for the second virtual host
    }
}

3. Symlink configuration files:

Create symbolic links to the configuration files in the `sites-enabled` directory to activate them:

sudo ln -s /etc/nginx/conf.d/example1.conf /etc/nginx/sites-enabled/
sudo ln -s /etc/nginx/conf.d/example2.conf /etc/nginx/sites-enabled/

4. Test configuration:

Check the configuration syntax for errors:

sudo nginx -t

If the syntax is correct, restart Nginx to apply the changes:

sudo systemctl restart nginx

5. Update DNS records:

Ensure that the DNS records for the domain names (e.g., www.example1.com, www.example2.com) point to the server's IP address.

6. Default server block:

If you have a default server block, it will be used when Nginx receives requests for domains that do not match any explicitly defined server block. Make sure it's configured appropriately.

8. Additional configuration:

You can add any other specific configurations based on your requirements. This could include access controls, logging settings, proxy configurations, ssl/tls Configurations, etc.

By following these steps, you can configure virtual hosts in Nginx to host multiple websites or applications on the same server. Each virtual host has its own set of configurations, allowing for flexibility and customization based on the specific needs of each website.
Topics

Mastering Nginx

27 articles

Bash script

2 articles

Crontab

2 articles