Create Apache Virtual host in Ubuntu 18.04
So this is something everyone struggles with while installing the LAMP stack on Ubuntu 18.04. I struggle too and I decided to note down the proper steps so we all can easily follow them in the future.
Before You follow the steps, just make sure to change example.com with your specific domain. And one more thing, these steps are tested locally. For publishing the live domain, there are different steps that I will post in the future after proper testing.
So here are the steps.
Step 1
Create project directory
sudo mkdir -p /var/www/example.com/public_html
Step 2
Add an HTML file in it for testing
sudo nano /var/www/example.com/public_html/index.html
And add the below code in it
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Welcome to example.com</title> </head> <body> <h1>Success! example.com home page!</h1> </body> </html>
Step 3
Add project directory to Apache www-data group.
sudo chown -R www-data: /var/www/example.com
Step 4
Create an apache config file for the project
sudo nano /etc/apache2/sites-available/example.com.conf
And add the below code in it
<VirtualHost *:80> ServerName example.com ServerAlias www.example.com ServerAdmin webmaster@example.com DocumentRoot /var/www/example.com/public_html <Directory /var/www/example.com/public_html> Options -Indexes +FollowSymLinks AllowOverride All </Directory> ErrorLog ${APACHE_LOG_DIR}/example.com-error.log CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined </VirtualHost>
Step 5
Enable new project as apache site. This creates some configuration files for apache automatically.
sudo a2ensite example.com
Step 6
Create a symlink of the project from sites-available folder to sites-enabled folder.
sudo ln -s /etc/apache2/sites-available/example.com.conf /etc/apache2/sites-enabled/
* Note: If this command does not work, just ignore it. Everything will be fine.
Step 7
Check if all configurations are done properly.
sudo apachectl configtest
It should show “Status OK”
Step 8
Restart Apache server
sudo systemctl restart apache2
Step 9
Edit hosts file to access the site using domain name locally
sudo nano /etc/hosts
And add the below code in it
127.0.0.1 example.com
Step 10
Add full access permission to the project folder so you can add/update/delete files and folders without using root.
sudo chmod -R 777 /var/www
And finally, try running http://example.com URL in the browser. It should show the example page we created in Step 2.
If you find this helpful, please share it with others and leave comments.
Thank You.