Apache redirect http to https URL
After installing ssl certificate in your website, you want to redirect all http traffic to https. This is required becuase modern browsers are preventing direct access to non https websites to open. Also this will prevent search engines to create bad-links for your website.
In this article, I will show you how you can redirect all of http traffic to https. In your website's root directory, there is .htaccess file. If there is no any file, create one file named .htaccess. This file works as apache configuration for this website only.
In this file add below mod_rewrite directive.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
You may need to restart the apache server with following command in command line server.
sudo service apache2 restart
The other way is redirect from apache virtual host. You have created virtual host for the website in /etc/apache2 directory. Open the website and add the below code in VirtualHost directive.
NameVirtualHost *:80
<VirtualHost *:80>
ServerName example.com
Redirect permanent / https://example.com/
</VirtualHost>
<VirtualHost _default_:443>
ServerName example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
# etc...
</VirtualHost>
Restart the apache server and all the http traffic will 301 redirect to https. It will also prevent serach engines to generate http links for your website.
Copyright 2023 HackTheStuff