Normally, to browse our website which is hosted in a local server(e.g. Apache) we need to write the website path something localhost/blog/index.php which is fine but not much convenient. Beside, this doesn’t look that much like real web address. What if we can access that browser something like, dev.blog.com? Won’t it be great? To achieve this we need to create a virtual host which will virtually make host like dev.blog.com that can be access through our browser. Here are the steps to create a virtual host:
Step 1. Open terminal go to /etc/apache2/sites-available
directory using the following command
cd /etc/apache2/sites-available
Step 2. Open a new file with .conf
extension. e.g. blog.conf
with the following command
sudo vim blog.conf
Step 3. Paste the following code(Root permission required) in the .conf file:
NameVirtualHost *:8080 Listen 8080 <VirtualHost *:8080> ServerAdmin example@domain.com ServerName dev.blog.com ServerAlias dev.blog.com DocumentRoot /var/www/blog/public <Directory /var/www/blog/public/> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all Require all granted </Directory> LogLevel debug ErrorLog ${APACHE_LOG_DIR}/blog_error.log CustomLog ${APACHE_LOG_DIR}/blog_access.log combined </VirtualHost>
Here, ServerAdmin
is the admin’s contacts. ServerName
is the url you want to access the site from browser.
DocumentRoot
is the root directory of your project. <Directory /var/www/blog/public>
here /var/www/blog/public
is also my project’s root directory where the index.php file is located
Step 4. Close the file and run the following command in terminal to enable the created virtual host:
sudo a2ensite blog.conf
Then reload the server with the following command:
sudo service apache2 reload
So, the virtual host is created and enabled now. If we enter dev.blog.com in our browser now it won’t show our site yet because the we have created the virtual host but that host is not known by our machine’s browser. To make it known to our machine we have to add our created virtual host’s URL into our host file(this is not required if you have bought a domain). So, let’s continue.
Step 5. Open the hosts file at /etc directory
sudo vim /etc/hosts
Add the following line in the hosts file:
127.0.0.1 dev.blog.com
Step 6. Save and enter dev.blog.com in any browser’s address bar, then HIT!
Our site is in dev.blog.com!! We are ready to GO :)