Important note on HTTP to HTTPS Redirections
It is important to keep the following in mind for HTTP redirections:
Websites may continue to listen on port 80 (HTTP) so that users do not get connection errors when typing a URL into their address bar, as browsers currently connect via HTTP for their initial request. Sites that listen on port 80 should only redirect to the same resource on HTTPS. Once the redirection has occured, HSTS should ensure that all future attempts go to the site via HTTP are instead sent directly to the secure site. APIs or websites not intended for public consumption should disable the use of HTTP entirely.
Redirections should be done with the 301 redirects, unless they redirect to a different path, in which case they may be done with 302 redirections. Sites should avoid redirections from HTTP to HTTPS on a different host, as this prevents HSTS from being set.
Basically, what this means is: Imagine you have www.example.com
as your website. After setting up your SSL certificate, you have example.com
and www.example.com
available through HTTP, and example.com
and www.example.com
available through HTTPS.
Now if you want to set up proper HTTP to HTTPS redirects, you must follow the rule that sites that listen on port 80 should only redirect to the same resource on HTTPS.
Here is a schematic redirect path for URL's:
http://example.com > 301 > https://example.com
https://example.com > 301 > https://www.example.com
http://www.example.com > 301 > https://www.example.com
Windows Server IIS
An HTTP to HTTPS redirect on IIS is often better left to the web server, with a simple httpRedirect redirection, than to a resource expensive URL Rewrite. This is easily done in a web.config IIS website configuration file. Where possible, use the IIS httpRedirect
element for a HTTP to HTTPS redirection, and here is how:
The regular expression matching of an URL Rewrite Module rule makes a rewrite rule rather expensive, resource wise. I'll provide an HTTP to HTTPS URL Rewrite example later in this post.
IIS httpRedirect
However, this httpRedirect
should be a little bit more performing, even though it may not be really noticeable. Shaving off milliseconds from a request and redirect HTTP to HTTPS instead of rewriting gives you a tiny bit faster responding website.
The httpRedirect
element configures settings for Internet Information Services (IIS) 7 that redirect client requests to a new location.
Let's say we want to redirect http://www.example.com and http://example.com to https://example.com. To httpRedirect
a HTTP request to HTTPS, you can add the following to your website's web.config
file, in the <system.webServer> </system.webServer>
node:
<httpRedirect enabled="true"
destination="https://example.com"
httpResponseStatus="Permanent"
/>
There are three important options configurable for the httpResponseStatus
:
IIS httpRedirect httpResponseStatus
- Found: Returns a 302 status code, which tells the client to issue a new request to the location specified in the destination attribute.
- Permanent: Returns a 301 status code, which informs the client that the location for the requested resource has permanently changed.
- Temporary: Returns a 307 status code, which prevents the client from losing data when the browser issues an HTTP POST request.
You may have to set up a new IIS Web Site and directory for the SSL website, to avoid a redirection loop.
An HTTP to HTTPS redirect on IIS is often better left to the web server, with a simple httpRedirect redirection, than to a resource expensive URL Rewrite.
Preserve URL Path Information and Query String in httpRedirect
Using a httpRedirect, you can preserve URL path information and URL query strings. Strangely enough, you need to set an exact destination for this:
exactDestination="true"
and you need to add $V$Q
to the destination URL:
destination="https://example.com$V$Q"
This makes our complete httpRedirect
element:
<httpRedirect enabled="true"
exactDestination="true"
destination="https://example.com$V$Q"
httpResponseStatus="Permanent"
/>
An URL with a query string, like http://www.example.com/page.php?foo=bar
, is now redirected to https://example.com/page.php?foo=bar
How to disable the httpRedirect to HTTPS
If you - for some reason - want to disable the httpRedirect temporarily, just set enabled
to false
:
<httpRedirect enabled="false"
destination="https://example.com"
httpResponseStatus="Permanent"
/>
Don't forget to enable HTTP Strict-Transport-Security (HSTS) on IIS. HSTS improves security and prevents man-in-the-middle attacks, downgrade attacks, and cookie-hijacking. And there are a number of different HTTP security headers that also need your attention.
Redirect HTTP to HTTPS Using IIS URL Rewrite Module in web.config
Did you know you can control IIS URL Rewrite Module and create rewrite rules using IIS Manager for Remote Administration? It's real easy to set it up on your Windows computer, see my step by step how to Install and setup IIS Manager for Remote Administration.
Here you'll find a ready to use IIS URL Rewrite Module rule for HTTP to HTTPS redirection. Depending on the particular situation, this solution might be preferred, and is easier to use than the aforementioned httpRedirect.
A ready and easy to use web.config IIS URL Rewrite Module rule to redirect HTTP to HTTPS is:
<!-- follow me on Twitter: @Jan_Reilink https://twitter.com/Jan_Reilink-->
<rule name="Redirect-HTTP-HTTPS-IIS">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
Save this code in your web.config file. If necessary, you can also add appendQueryString="true"
to the action, to append the query string to the rewritten URL.
You have to place the code in the system.webServer
node of your web.config
file.
Test your site, it should now redirect from HTTP to HTTPS. If you receive a too many redirects in your browser, you may have to add your domain name as an input condition.
<!-- Redirect HTTP naar HTTPS for WordPress:
/posts/ssl-wordpress-move-wordpress-site-https-definitive-guide/
-->
<rule name="example.com http to https" stopProcessing="true">
<match url="(.*)" ignoreCase="true" />
<conditions logicalGrouping="MatchAll">
<add input="{HTTP_HOST}" pattern="^(www.)?example\.com$" />
<add input="{HTTPS}" pattern="off" />
<add input="{URL}" pattern="(.*)" />
</conditions>
<action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
</rule>
This rule also automatically adds the request_uri ({URL}
) to the redirected HTTPS URL.
How to rewrite multiple sub domains in one URL Rewrite Module Rewrite rule
To rewrite multiple sub domains in one single URL Rewrite rule you can use:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="Rewrite multiple sub domains" stopProcessing="true">
<match url=".*" ignoreCase="false" />
<conditions trackAllCaptures="true">
<add input="{HTTP_HOST}" pattern="^(?!www)([^.]+)\.(example\.com)" />
<add input="{URL}" pattern="(.+)" ignoreCase="false" />
</conditions>
<action type="Rewrite" url="/{C:1}" appendQueryString="true" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
Add
appendQueryString="true"
to the action to append the query string in your HTTPS rewrite.
Redirect HTTP to HTTPS on Apache 2.4
The last few day's I've been toying with Nagios, setting up a monitoring system. An Apache redirect to HTTPS was one of the tasks I wanted to accomplish. This would redirect the Nagios vhost from HTTP to HTTPS using an Apache 2.4.6 VirtualHost, and no resource expensive rewrite would be necessary.
HTTP to HTTPS redirect in Apache - using VirtualHosts
Apache's mod_alias
provides the Redirect
and RedirectMatch
directives, which provide a means to redirect one URL to another. This kind of simple redirection of one URL, or a class of URLs, to somewhere else, should be accomplished using these directives rather than a mod_rewrite RewriteRule
.
The Redirect directives are used to instruct clients to make a new request with a different URL. They are often used when a resource has moved to a new location (source).
Create Apache VirtualHost directives for HTTP and HTTPS
The first step in redirecting HTTP traffic to HTTPS in Apache is to create two VirtualHost directives for your website. One for HTTP (*:80) and one for HTTPS (*:443).
The next step is to use the Redirect directive to redirect one VirtualHost to another. See the following, complete, VirtualHost configuration to redirect Nagios from HTTP to HTTPS on Apache:
<VirtualHost *:443>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName www.example.com
ServerAdmin admin@example.com
DocumentRoot /data/example.com/http/
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
# LogLevel info ssl:warn
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
# Include conf-available/serve-cgi-bin.conf
ScriptAlias /cgi-bin/ "/data/example.com/http/cgi-bin/"
AddHandler php5-script .php
AddHandler cgi-script .pl .cgi
DirectoryIndex index.php
AddType text/html .php
<Directory "/data/example.com/http/">
Options None
AllowOverride None
</Directory>
<Directory "/data/example.com/http/cgi-bin/">
AllowOverride None
Options ExecCGI
</Directory>
ErrorLog /data/log/example.com/ssl-error.log
CustomLog /data/log/example.com/ssl-access.log combined
SSLEngine On
SSLCertificateFile /data/example.com/ssl/example.com.crt
SSLCertificateKeyFile /data/example.com/ssl/example.com.key
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /data/example.com/http/
ErrorLog /data/log/example.com/error.log
CustomLog /data/log/example.com/access.log combined
Redirect / https://www.example.com/
</VirtualHost>
Apache's
mod_alias
provides theRedirect
andRedirectMatch
directives, which provide a means to redirect one URL to another. Use this to set up an Apache 2.4 redirect from HTTP to HTTPS.
The Redirect / https://www.example.com/
line is what redirects HTTP traffic to HTTPS, e.g from http://www.example.com to https://www.example.com. The rest of the VirtualHost configuration is pretty much self explanatory.
But what if you don't have access to your Apache VirtualHost config, and still want to use a Redirect and not a resource expensive Redirect? Well, you can use the following condition in a .htaccess
file in your site's document root:
<If "%{HTTPS} != 'on'">
Redirect permanent "/" "https://www.saotn.org/"
</If>
Apache 2.4.6 Require all granted
One issue you might find upgrading Apache to version 2.4.6 is you have to use Require all granted
instead of Order allow,deny
and Allow from all
when using Access Control:
# 2.2 configuration:
Order allow,deny
Allow from all
# 2.4 configuration:
Require all granted
See my .htaccess security best practices in Apache 2.4 post for more information on this access control topic.