How to Redirect HTTP to HTTPS in Apache


redirect from http to https

HTTPS protocol makes your websites more secure by encrypting all the data between users’ web browsers and your server. Moving your website from HTTP to HTTPS also improves your search engine rankings. Here’s how you can redirect HTTP to HTTPS in Apache.

Before you can setup HTTP to HTTPS redirect for your domain, make sure you have installed SSL certificates on your Apache server.

 

How to Redirect HTTP to HTTPS in Apache (using .htaccess)

First step is to ensure that mod_rewrite module is enabled in Apache. On Debian systems, it is enabled by default.

For Ubuntu/CentOS systems, you’ll need to enable it explicitly


$ sudo a2enmod rewrite

 

For RHEL systems, ensure that you have the following lines in httpd.conf


LoadModule rewrite_module modules/mod_rewrite.so

 

Next, either create or edit .htaccess file in your domain’s root folder and add the lines


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

 

Restart Apache server to apply changes


$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]

Now when users visit the HTTP version of your website pages, they’ll be redirected to their HTTPS versions.

 

Using .htaccess allows you to set up redirects without modifying server configuration files. However, if you want to modify server config files then you can modify the httpd.conf file.

In fact, Apache recommends against using .htaccess file for redirecting to HTTPS. Instead, it advises you to use redirects in main server configuration file, NOT .htaccess file

 

How to Redirect HTTP to HTTPS in Apache (using httpd.conf)

Open server configuration file (httpd.conf) and add the following lines.


<VirtualHost *:80>
 ServerName www.example.com
 Redirect "/" "https://www.example.com/"
</VirtualHost>

<VirtualHost *:443>
 ServerName www.example.com
 # ... SSL configuration goes here
</VirtualHost>

Restart Apache server to apply changes


$ sudo systemctl restart apache2 [Ubuntu/Debian]
$ sudo systemctl restart httpd [RHEL/CentOS]

Between the 2 methods, Apache recommends using <VirtualHost> because it is simpler and more secure.

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!