Redirect HTTP to HTTPS in Apache

Apache HTTP ServerLet’s say you want all traffic to your website use secured connection. You can redirect HTTP to HTTPS in Apache like following:

Using virtual hosts and Redirect directive

When using SSL, you will frequently have at least two virtual hosts: one on port 80 to serve ordinary requests, and one on port 443 to serve SSL. If you wish to redirect users from the non-secure site to the SSL site, you can use an ordinary Redirect directive inside the non-secure VirtualHost:

To redirect one page:

To redirect everything you don’t need a DocumentRoot:

Once the configuration is working as intended, a permanent redirection can be considered. This avoids caching issues by most browsers while testing. The directive would then become:

Using .htaccess files and redirect

Redirect can also be used inside .htaccess files or to address particular URLs, as in:

Example:

Using mod_rewrite

Using the mod_rewrite rule is recommended for experienced users, as the exact configuration can be different on different systems. The syntax of mod_rewrite rules can be complicated – for example, if you would like to redirect to HTTPS certain subfolders that consist of other subfolders. If you are not sure whether mod_rewrite can be used, it is better to enable the redirect to HTTPS in the virtual host file. If you would like to create a redirect for certain pages, the mod_rewrite rule should look like this:

The redirect for all directories is similar and looks like this:

Note: To set a redirect with a 301 status code (permanent), you will need to assign this code to the R-flag in brackets by adding “=301”.

Now your website will be available via HTTPS by default. To check if the redirects work correctly, please clear the cache in the browser you usually use and open your website or try checking it in another browser.

Want me to do this for you? Drop me a line: itgalaxyzzz {at} gmail [dot] com