If you’re running your website on an Apache server, there are two main ways to force it to load over HTTPS instead of HTTP: either by editing the main Apache config files or by using a .htaccess file. For most of us, especially if you’re on shared hosting, the .htaccess method is the easier and more accessible option. In this quick guide, I’ll show you how to redirect all HTTP traffic to HTTPS using .htaccess, so your visitors always land on the secure version of your site. It’s simple, effective, and good for both security and SEO.
Prerequisites
-
- You need access to the web server via SSH.
- A valid SSL certificate must be Installed and properly configured.
To redirect all HTTP traffic to HTTPS using the .htaccess file in an Apache server, follow these steps:
1) Locate Your .htaccess File
Usually found in the root directory of your website (/var/www/html/ or similar).
If it doesn’t exist, create a new file named .htaccess.
2) Add HTTPS Redirect Code
Paste the following code into your .htaccess file:
RewriteEngine On
# Redirect HTTP to HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Explanation:
-
- RewriteEngine On : Enables the rewrite module.
- RewriteCond %{HTTPS} off : Checks if the request is not using HTTPS.
- RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} : Redirects to the HTTPS version of the current URL.
- [L,R=301] : Tells Apache to send a permanent redirect (301) and stop processing further rules.
Requirements:
The mod_rewrite module must be enabled:
Run:
-
- sudo a2enmod rewrite
- sudo systemctl restart apache2
An SSL certificate must be installed and properly configured for the domain.
Test:
After editing, visit your site with http://example.com and confirm it redirects to https://example.com.
Conclusion
Redirecting HTTP to HTTPS with the .htaccess file is a quick and important step to help secure your website and boost your SEO. Forcing all traffic through HTTPS means everything’s encrypted and trusted by browsers and search engines. Just double-check that your SSL certificate is installed correctly and that Apache’s mod_rewrite module is turned on. Once it’s set up, your site will automatically send visitors to the secure version—making things safer and more professional for everyone who stops by.