+5 votes
213 views
How to create Apache Virtual Host in Ubuntu LTS

in Web Servers by (551k points)
reopened | 213 views

1 Answer

+3 votes
Best answer

Create the home page
Create the Virtual Host of Fulanito
Create the Menganito Virtual Host
Using the Script to create a new domain

image

This time I bring a manual on how to manage multiple domains with the same IP address in the Apache web server , which is common in Shared Hosting, an ideal solution in test environments even in production to offer an extra level of security..

What is Apache?

The Apache HTTP server is an open source web server for Unix-like platforms , Windows including Mac includes HTTP protocols and Virtual Site option. It is the most popular web server in the world (since 1996) since it is very stable as well as optimal security (being well configured). Apache is the server that continues to be developed under Apache Software Foundation programmers.
Main features of Apache

Among the main features are:
  • SSL and TLS security for encrypted connections (HTTPS).
  • SGDB (Data Authentication).
  • Support with programming languages ​​such as perl, php, python.
What is a Virtual Hosts ?

The virtual term hosts refers to the practice of running one or more webs of different domains in the same IP address using port redirection internally for each domain. You could define a Virtual Host as the method of a shipping company to transfer each package to the corresponding branch, apache was one of the first web servers to support virtual hosts based on IP without installing any additional plugin. After version 1.1, support is added to the creation of Virtual Host based on IP and names .
Differences between the vitual hosting based on names and the IP based

Apache supports 2 ways to configure a virtualhost:
  • By IP
  • By domain names
In the solution for IP apache is set the IP of the client that makes the request and according to the range of Ip you have predefined you can enter site A or B this in conjunction with a geolocation by Ip is very advantageous in pages with several languages .

The virtual hosting based on names is usually simpler , it is the one that we will apply in the laboratory, it is only necessary to configure the DNS Server, either external or local, so that it points to our server that will filter the HTTP header and redirect it accordingly. to the right place. The biggest advantage is that you can dramatically reduce the number of IP addresses per domain otherwise by IP redirection where you would need a Public IP for each different site. You will have situations in which you will not be able to implement hosting based on names for different reasons that are listed:

  • Some older web browsers are not compatible with name-based virtual hosting. For the name-based virtual hosting to work, the client must send the HTTP Host header.
  • Virtual hosting based on names can not be used together with SSL If you want to implement HTTPS is not your option.
  • Some operating systems and some network elements have implemented bandwidth management techniques that can not differentiate between hosts unless they are in different IP addresses.
Preparing the System.

To configure the Virtual Host it is necessary to install the Apache server which is included in the Ubuntu Repositories .
 sudo ap-get install apache2 
Once installed, we can run it with:
 sudo service apache start 
We create a user without administrator rights that will be the owner of the web server files:
 useadd fulanitopasswd so-so # Enter the password for the user 
This way it will be without administrator permissions.
Create Directory

We must create the structure of the directories that will maintain the information of the sites.

Our root document must be configured in the individual directories that usually go within the / var / www path. Here we will create the directories for the two Virtual Hosts that we will configure as an example. To create the directory you can use the -p option of the mkdir command, so that it will create all the necessary directories and subdirectories.

 sudo mkdir -p /var/www/fulanito.com/httpdocssudo mkdir -p /var/www/menganito.com/httpdocs 
This will be the root directory of the 2 Domains.
Give permissions

To give the user permission to work with the files of the directories, I recommend using the non-root user that we have created and additionally enable their access via FTP or SFTP
 sudo chown -R fulanito.fulanito /var/www/fulanito.com/httpdocssudo chown -R menganito.menganito /var/www/menganito.com/httpdocs 
Your server now has the necessary permissions to display the content, and the user should be able to create content in the directories as needed.

Create the home page


We're just going to do a demonstration, so our pages will be very simple. We will only create an index.html file for each site.
 sudo touch /var/www/fulanito.com/public_html/index.htmlsudo touch /var/www/menganito.com/public_html/index.html 
We started with the so-and-so file so we use our favorite editor in my case vim.
 sudo vim /var/www/fulanito.com/public_html/index.html 
 <html> <head> <title> You have entered the website of Fulanito </ title> </ head> <body> <h1> Perfect! You already have the Virtual Host of Fulanito </ h1> </ body> </ html> 
We save the file with: wq in case of using vim and we start with menganito.
 sudo vim /var/www/menganito.com/public_html/index.html 
 <html> <head> <title> You have entered the site of Menganito </ title> </ head> <body> <h1> Perfect! You have already configured the Menganito Virtual Host </ h1> </ body> </ html> 
Save the file and exit the editor.
Create files of the new Virtual Hosts

Virtual Host files are files that contain information and specific configuration for each domain, for example we can have a global Apache configuration and independent options for a specific domain.

Apache includes a default Virtual Host file named 000-default.conf that we can use to jump to the point. We will make a copy to work on it and create our Virtual Host for each domain..

We will start with a domain, configure it, copy it for the second domain, and then make the necessary adjustments. The default configuration of Ubuntu requires that each Virtual Host configuration file end in .conf.

Create the Virtual Host of Fulanito


We start by copying the default apache file that comes by default and use it as a base.
 sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/fulanito.com.conf 
Then we edit it and change the values ​​for our domain and root location.
 sudo vim /et/apache2/sites-available/fulanito.com 
We will edit the name of the domain that will be used by the virtual host, which in this case is so-and-so.
 ServerName fulanito.com 
If we want our site to be accessible through more than one domain name (practice used by google), you must add it in the ServerAlias , in the following way.
 <VirtualHost *: 80> ServerName fulanito.com ServerAlias ​​www.fulanito.com fulanitooo.com www.fulanitooo.com ... 
Remember that you must have access to the public domains that you add in ServerAlias , in my case it will not be necessary because it will be all local.

The next thing will be to add the mail of the webmaster who will be in charge of the administration..

 ServerAdmin [email protected] 
And Add the folder Root of our Domain.
 DocumentRoot /var/www/fulanito.com/httpdocs 

Create the Menganito Virtual Host


We continue this time with the domain of menganito and copy directly from the file of so-and-so.
 sudo cp /etc/apache2/sites-available/fulanito.com.conf /etc/apache2/sites-available/menganito.com.conf 
We edit to make it look like this:
 <VirtualHost *: 80> ServerAdmin [email protected] ServerName menganito.com ServerAlias ​​www.menganito.com DocumentRoot /var/www/menganito.com/httpdocs ErrorLog $ {APACHE_LOG_DIR} /error.log CustomLog $ {APACHE_LOG_DIR} /access.log combined </ VirtualHost> 
We keep the changes.
Enable new domains in Apache

We must enable the access of the new sites for Apache to take them into account after restarting we use:
 sudo a2ensite fulanito.comsudo a2ensite menganito.com 
Finally restart the Apache server :
 sudo service apache2 restart 
It is possible that the system displays a message similar to this one:
 Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName 
As it is a warning message, we have no problems and will not prevent us from accessing the new sites.
Configure Hosts

This step is optional, if you have access to paid public domains we can skip the step, in my case as it is a lab and the domains are false I must edit the file / etc / hosts of my local machine.

In case of Linux we must edit the file:

 sudo vim / etc / hosts 
In case of windows we must edit the file with the notebook in administrator mode:
 C: \ Windows \ System32 \ drivers \ etc \ hosts 
Any of the Operating Systems the file is very similar and we must add the domains at the end:
 # Host Database ## localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 127.0.0.1 localhost # Virtual Hosts 127.0.0.1 fulanito.com127.0.0.1 menganito.com ... 
This is very useful while you are developing the website before uploading it to the server, so that you can navigate and test as if you do it in real.

In order for the changes made in the / etc / hosts file to take effect, the following command can be executed:

 sudo /etc/init.d/networking restart 
Test your Apache server
image image
Script to add Virtual Host

The task of the Vhost is very common and repetitive to finish add a small script in bash so you can automate this task on servers with ubuntu more quickly.
 #! / bin / bash TEXTDOMAIN = Example.com ### Define the Arguments in this order Action, Domain and Root Directory. action = $ 1 domain = $ 2 rootDir = $ 3 owner = $ (who am i | awk '{print $ 1}') email = 'webmaster @ localhost' sitesEnable = '/ etc / apache2 / sites-enabled /' sitesAvailable = '/ etc / apache2 / sites-available /' userDir = '/ var / www /' sitesAvailabledomain = $ sitesAvailable $ domain.conf ### DO NOT CHANGE if ["$ (whoami)"! = 'root']; then echo $ "You do not have permission to run it $ 0 as an unprivileged user. Use sudo" exit 1; fi if ["$ action"! = 'create'] && ["$ action"! = 'delete'] then echo $ "You must specify an action {create, delete}" exit 1; fi while ["$ domain" == ""] do echo -e $ "Enter a domain for example example.com" read domain done if ["$ rootDir" == ""]; then rootDir = $ {domain //./} fi ### if root dir starts with '/', do not use / var / www as default starting point if [["$ rootDir" = ~ ^ /]]; then userDir = '' fi rootDir = $ userDir $ rootDir if ["$ action" == 'create'] then ### check if domain already exists if [-e $ sitesAvailabledomain]; then echo -e $ "The domain already exists please add another." exit; fi ### check if directory exists or not if! [-d $ rootDir]; then ### create the directory mkdir $ rootDir ### give permission to root dir chmod 755 $ rootDir ### write test file in the new domain dir if! echo "<? php echo phpinfo ();?>"> $ rootDir / phpinfo.php then echo $ "ERROR: Insufficient permissions to write to the $ userDir / $ rootDir / phpinfo.php directory Verify your permissions" exit; else echo $ "Added content to $ rootDir / phpinfo.php" fi fi ### create virtual host rules file if! threw out " <VirtualHost *: 80> ServerAdmin $ email ServerName $ domain ServerAlias ​​$ domain DocumentRoot $ rootDir <Directory /> AllowOverride All </ Directory> <Directory $ rootDir> Options Indexes FollowSymLinks MultiViews AllowOverride all Requires all granted </ Directory> ErrorLog /var/log/apache2/$domain-error.log LogLevel error CustomLog /var/log/apache2/$domain-access.log combined </ VirtualHost> "> $ sitesAvailabledomain then echo -e $ "There is an ERROR creating $ domain file" exit; else echo -e $ "\ nNew Virtual Host Created \ n" fi ### Add domain in / etc / hosts if! echo "127.0.0.1 $ domain" >> / etc / hosts then echo $ "ERROR: Not able to write in / etc / hosts" exit; else echo -e $ "Host added to / etc / hosts file \ n" fi if ["$ owner" == ""]; then chown -R $ (whoami): $ (whoami) $ rootDir else chown -R $ owner: $ owner $ rootDir fi ### enable website a2ensite $ domain ### restart Apache /etc/init.d/apache2 reload ### show the finished message echo -e $ "Complete! \ nYou now have a new Virtual Host \ nYour new host is: http: // $ domain \ nAnd its located at $ rootDir" exit; else ### check whether domain already exists if! [-e $ sitesAvailabledomain]; then echo -e $ "This domain does not exist. \ nPlease try another one" exit; else ### Delete domain in / etc / hosts newhost = $ {domain //./ \\.} sed -i "/ $ newhost / d" / etc / hosts ### disable website a2dissite $ domain ### restart Apache /etc/init.d/apache2 reload ### Delete virtual host rules files rm $ sitesAvailabledomain fi ### check if directory exists or not if [-d $ rootDir]; then echo -e $ "Delete host root directory? (and / n)" read deldir if ["$ deldir" == 'y' -o "$ deldir" == 'Y']; then ### Delete the directory rm -rf $ rootDir echo -e $ "Directory deleted" else echo -e $ "Host directory conserved" fi else echo -e $ "Host directory not found. Ignored" fi ### show the finished message echo -e $ "Complete! \ nYou just removed Virtual Host $ domain" exit 0; fi 

Using the Script to create a new domain


We will make a new vhosts for zutano domain.
 sudo virtualhost create zutano.com /var/www/zutano.com/httpdocs 
With that, it will be created.
Conclusions
We have created a small lab for 3 false domains that respond to an address, when using vhosts with NAT we can create staging sites for example dev.fulanito.com to make modifications in a replica without affecting the original site. The steps for other Distros such as Centos vary in some steps but are very similar by changing the package manager.

by (3.5m points)
edited

Related questions

+5 votes
1 answer
asked May 12, 2019 in Linux / Unix by backtothefuture (551k points) | 181 views
+5 votes
1 answer
+5 votes
1 answer
+5 votes
1 answer
+3 votes
1 answer
Sponsored articles cost $40 per post. You can contact us via Feedback
10,634 questions
10,766 answers
510 comments
3 users