DEV Community

Imran Hossain (Rubab)
Imran Hossain (Rubab)

Posted on • Edited on

Virtual Host Setup with SSL Certificate in Your Localhost

Image description

In this article we will learn how we can run our project from a custom url example.com instead of localhost in our local LAMP Server on Ubuntu.

First open your terminal and create a New file called example.com.conf with root privileges.

touch /etc/apache2/sites-available/example.com.conf

Open the new file with root privileges.
sudo nano /etc/apache2/sites-available/example.com.conf

Add below lines in the example.com.conf file.

<VirtualHost *:80>
  ServerName example.com
        DocumentRoot /var/www/html/example-project
  Redirect permanent / https://example.com
</VirtualHost>
<VirtualHost *:443>
  ServerAdmin example@example.com
        DocumentRoot /var/www/html/example-project
  ServerName example.com

  SSLEngine on
  SSLCertificateFile /var/www/html/ssl/server.crt
  SSLCertificateKeyFile /var/www/html/ssl/server.key
  SSLCertificateChainFile /var/www/html/ssl/rootCA.pem

  <Directory "/var/www/html/example-project">
    Options Indexes FollowSymLinks
    AllowOverride All
        Require all granted
  </Directory>

  ErrorLog ${APACHE_LOG_DIR}/error.log
  CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
Enter fullscreen mode Exit fullscreen mode

As you can see we have added http with port 80 and https with port 443. We have also added redirection to example.com to https://example.com

For SSL certificate, Please create a ssl certificate and then add the crt, key and pem type files in a ssl folder under /var/www/html folder. Please note that we have mentioned path for the crt, key and pem files for VirtualHost port 443 above. Finally, we enabled htaccess by “AllowOverride All”.

Now save the file and it’s time to add our custom host to the host file.

Open the host file in terminal by the command
sudo nano /etc/hosts

Add our example.com to the end of file.

127.0.0.1   localhost
.....
.....
127.0.1.1   example.com // add this line
Enter fullscreen mode Exit fullscreen mode

To enable SSL and new vhost config file use these commands
sudo a2enmod ssl // to enable ssl
sudo a2ensite example.com.conf // to enable vhost config

Now restart the server to apply the changes
sudo systemctl restart apache2

Test it now by visiting example.com

If we face any problem then we will be able to see in /var/log/apache2/error.log file.


Thank you for reading my article. You can join code with rubab for web development-related queries & discussions.

Also, you can find me on:

Linkedin For Regular Posts

My website

My Facebook Page

My Youtube Channel

Top comments (0)