To enable HTTP and HTTPS on localhost in Ubuntu, you typically need a web server like Apache or Nginx. Below are the steps to set up both HTTP and HTTPS on localhost using Apache as the web server:
Install Apache:
sudo apt update
sudo apt install apache2Enable Apache's SSL module:
sudo a2enmod sslGenerate a Self-Signed SSL Certificate:
sudo mkdir /etc/apache2/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache.key -out /etc/apache2/ssl/apache.crtThis command will create a self-signed SSL certificate valid for 1 year.
Configure Apache for HTTPS:
Create or edit an Apache configuration file for your localhost:
sudo nano /etc/apache2/sites-available/localhost.confAdd the following configuration:
<VirtualHost *:443>
ServerName localhost
DocumentRoot /var/www/html
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/apache.crt
SSLCertificateKeyFile /etc/apache2/ssl/apache.key
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>Save and close the file.
Enable the HTTPS site:
sudo a2ensite localhost.confRestart Apache:
sudo systemctl restart apache2Adjust Firewall (if necessary):
If you have UFW enabled, allow HTTPS traffic:
sudo ufw allow 'Apache Full'Testing:
- Open your web browser and visit https://localhost. You should see the default Apache landing page or whatever content you have in /var/www/html.
Now, HTTP is already enabled by default when you install Apache. So, if you want to use both HTTP and HTTPS simultaneously, you need to add another VirtualHost configuration for HTTP.
Configure Apache for HTTP:
Edit the Apache configuration file:
sudo nano /etc/apache2/sites-available/localhost.confAdd a new VirtualHost block for HTTP:
<VirtualHost *:80>
ServerName localhost
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Save and close the file.Enable the HTTP site:
sudo a2ensite localhost.confRestart Apache:
sudo systemctl restart apache2Now you have both HTTP and HTTPS enabled for your localhost on Ubuntu using Apache. You can access your content via http://localhost and https://localhost.
