Last updated on November 6th, 2024 at 12:51 pm
If your webserver is running on Apache, after configuring SSL for your website, the subsequent step is to ensure that all visitors are automatically redirected from HTTP to HTTPS. This automatic redirection can be achieved by utilizing the .htaccess file.
All you have to do is create (If you don’t have one) htaccess file in the Website root directory. Make sure that mod_rewrite is enabled on your Apache configuration file [httpd.conf]
For example my root directory is /usr/local2/www, create a .htaccess file in this location with the content below
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
If you already have a .htaccess file with statement “RewriteEngine On” then all you need to do is add these two statements
RewriteCond %{HTTPS} !=on RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This verifies whether the requested URL includes “https”; if it does not, the URL will be rewritten according to the established rule.
HTTP_HOST will be your hostname, and the REQUEST_URI will be the URI of your hostname.
- [L] Last rewrite rule and stop the rule if it matches.
- [R=301] means it is a permanent URL redirect
- ^ Caret symbol matches the start of a string/url
https://%{HTTP_HOST}%{REQUEST_URI}
For example if the URL requested by a user is http://webtutorials.dev/archives/html, Then internally the server will redirect this URL to HTTPS https://webtutorials.dev/archives/html
In this HTTP_HOST is webtutorials.dev and REQUEST_URI is wp/archives/html