Let’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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
NameVirtualHost *:80 <VirtualHost *:80> ServerName mysite.example.com DocumentRoot /usr/local/apache2/htdocs Redirect /secure https://mysite.example.com/secure </VirtualHost> <VirtualHost _default_:443> ServerName mysite.example.com DocumentRoot /usr/local/apache2/htdocs SSLEngine On # etc... </VirtualHost> |
To redirect everything you don’t need a DocumentRoot:
1 2 3 4 5 6 7 8 9 10 11 12 |
NameVirtualHost *:80 <VirtualHost *:80> ServerName www.example.com Redirect / https://secure.example.com/ </VirtualHost> <VirtualHost _default_:443> ServerName secure.example.com DocumentRoot /usr/local/apache2/htdocs SSLEngine On # etc... </VirtualHost> |
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:
1 |
Redirect permanent / https://secure.example.com/ |
Using .htaccess files and redirect
Redirect can also be used inside .htaccess files or to address particular URLs, as in:
Example:
1 |
Redirect /login https://mysite.example.com/login |
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:
1 2 3 |
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/?secure/(.*) https://%{SERVER_NAME}/secure/$1 [R,L] |
The redirect for all directories is similar and looks like this:
1 2 3 |
RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] |
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.