Setting up virtual host in Linux for Apache server

Published Apr 25, 2017 on Web by Al Imran Ahmed

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:

<VirtualHost *:80>
ServerAdmin al.imran.cse@blog.com
ServerName dev.blog.com
# SetEnv APPLICATION_ENV development
# ServerAlias dev.blog.com
# SetEnv APPLICATION_COUNTRY GBR
DocumentRoot /var/www/blog/public
DirectoryIndex index.php
<Directory/>
Options FollowSymLinks
AllowOverride all
</Directory>
<Directory /var/www/blog/public>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all
Require all granted
</Directory>;
 
ErrorLog ${APACHE_LOG_DIR}/error-blog.log
 
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn
CustomLog ${APACHE_LOG_DIR}/access-blog.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 :)

Comments(1)

+

Moshiur Rahman said

Thank you brother really helpful this article is
No noise, unsubscribe anytime!
© 2023 Al Imran Ahmed
Proudly build with: Larablog
Contact