hkucuk

Creating a Virtual Host for a Subdirectory

October 22, 2018 • ☕️ 2 min read • 🏷 computer, software

Translated by author into: DeutschEnglishItalianoРусский


Virtual Host is used when we want to host more than one site on a server. For example, we have 3 domain and 3 different projects on the server.

  1. example.com ---> /var/www/example
  2. example2.com ---> /var/www/example2
  3. example3.com ---> /var/www/example3

To enable these domains to run projects in folders indicated by arrows, we need to make virtual host definitions. To do this, we will do the following description.

<VirtualHost *:80>
    DocumentRoot "/var/www/example"
    ServerName example.com
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/var/www/example2"
    ServerName example2.com
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/var/www/example3"
    ServerName example3.com
</VirtualHost>

The above definitions enable us to run different projects for different domains. But how can we provide different sub-directories to run different projects within the same domain with Virtual Host?

For this, we need to make a new addition to the above definition. For example, let’s say that we have one domain and 3 different projects.

  1. example.com ---> /var/www/example
  2. example.com/alt1 ---> /var/www/example2
  3. example.com/alt2 ---> /var/www/example3

To enable these domains and subdirectories to run projects indicated by arrows, it is enough to organize our Virtual Host definitions as follows.

<VirtualHost *:80>
    DocumentRoot "/var/www/example"
    ServerName example.com

    Alias /alt1 "/var/www/example2"
    Alias /alt2 "/var/www/example3"
</VirtualHost>

Referances

  1. https://httpd.apache.org/docs/2.4/tr/vhosts/index.html
  2. https://httpd.apache.org/docs/2.4/tr/vhosts/examples.html
  3. https://serverfault.com/questions/497541/virtual-host-on-a-sub-directory
  4. https://stackoverflow.com/questions/19055372/redirect-to-a-subfolder-in-apache-virtual-host-file
  5. https://httpd.apache.org/docs/2.4/tr/vhosts/name-based.html