To redirect non-SSL (HTTP) traffic to SSL (HTTPS) using an .htaccess
file in an Apache web server, you can use the following directives.
-
Create or edit the
.htaccess
file in the root directory of your website (or the specific directory where you want to enforce SSL). -
Add the following code to the
.htaccess
file:<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </IfModule>
-
Save the
.htaccess
file.
Let's break down what each line does:
RewriteEngine On
: Enables the Apache rewrite engine.RewriteCond %{HTTPS} !=on
: Checks if the current request is not using HTTPS.RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
: Redirects the user to the same requested URL, but withhttps://
at the beginning. The[L,R=301]
flags indicate that it's the last rule and it's a permanent (301) redirect.
After making these changes, any user accessing your site via non-SSL (HTTP) will be automatically redirected to the SSL (HTTPS) version of the same page.