- sarbatrainc
- August 21, 2020
- No Comments
Virtual Host in Linux
Every once in a while you try to develop a web application, you create a project under /var/www/html (or somewhere equivalent) and you access the project using localhost. This is old fashioned. Lets step up a bit. Best way to develop any web application is to simulate the actual web server the web application will be hosted into. Lets remove the localhost altogether and use the domain name in the local server instead of the trivial localhost.
Lets say that you have apache installed in your system. If not then
$ sudo apt-get install apache2or
$ sudo yum install apache2Go ahead I will be waiting for you! Well then, you have your apache. Now as you can see or already know, the apache home page is opened by http://localhost and any other projects are opened by adding up the projects name to the localhost url. In using this you may feel as if this is not how the actual website is displayed, and since this is just a development it doesnt really matter much. But guess WHAT!!! It matters. You see working with localhost has its drawbacks. When you get the actual REQUEST_SERVER url, you will get localhost rather than localhost/yourProjectFolderName. So your project folder should be added manually added by you and later adjusted when you are live-ing your project. This may result in some internal issues. So how do we remove the localhost and use a domain name locally you say? We use Virtual Hosts. localhost is also a virtual host that has been set up by default for the path /var/www/html by apache. So if we need to create a new domain we need to create a new virtual host. Its not that hard. We just need to edit 2 files altogether. So lets get right to it. Lets say I want to run my project http://localhost/myproject under myproject.com locally Firstly, got to /etc/apache2/sites-available and then create a new .conf file.
$ cd /etc/apache2/sites-available/ $ sudo gedit myproject.confthen copy these lines of code in myproject.conf. Save it and close it.
<VirtualHost *:80>
ServerName myproject.com
#ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/myproject
SetEnv "APPLICATION_ENV" "development"
<Directory /var/www/html/myproject>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Now enable the virtual host.
$ sudo a2ensite /etc/apache2/sites-available/myproject.confWe are half way through, now we need to edit the /etc/hosts file.
$ sudo vim /etc/hostsand add line
127.0.0.1 myproject.com
just below 127.0.0.1 localhost
Finally, restart apache server
$ sudo service apache2 restartAnd we are good to go. Test the url in your browser and see if the project works.
Leave A Comment