Redirect to https using .htaccess file [Resolved]


To set up a permanent (301) redirect from HTTP to HTTPS using the .htaccess file, you can add the following code snippet to your website’s .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This code uses mod_rewrite in Apache to check if the request is not using HTTPS (RewriteCond %{HTTPS} !=on). If it’s not, the rule redirects the request to the HTTPS version of the same URL (RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]).

Make sure you have mod_rewrite enabled on your server. If you’re unsure, you can check by looking for the presence of the following line in your Apache configuration:

LoadModule rewrite_module modules/mod_rewrite.so

Once you’ve added the code to your .htaccess file, any HTTP requests will be automatically redirected to their corresponding HTTPS URLs using a permanent (301) redirect. Always make sure to have a backup of your .htaccess file before making changes, and ensure you’re familiar with the server configuration.