DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 5.15 Redirecting All—or Part—of Your Server to SSL

Problem

You want certain parts of your non-SSL web space to be redirected to a secured area.

Solution

You can redirect everything that is attached to port 80 with the following RewriteRule:

RewriteCond "%{SERVER_PORT}"       "^80$"
RewriteRule "^(.*)$"               "https://%{SERVER_NAME}$1" [R,L]

You can redirect particular URLs to a secure version:

RewriteRule "^/normal/secure(/.*)" "https://%{HTTP_HOST}$1" [R,L]

You can check to see whether the HTTPS environment variable is set:

RewriteCond %{HTTPS} !=on
RewriteRule "^(/secure/.*)" "https://%{HTTP_HOST}$1" [R,L]

Or, you can simply use the Redirect directive in the http section of httpd.conf file to to cause a URL to be served as HTTPS:

Redirect / https://secure.example.com/

Make sure that this appears only in in the http scope and not in the https scope, or all https requests will loop.

Discussion

The first solution causes all requests that come in on port 80 (normally the unencrypted HTTP port) to be redirected to the same locations on the current server but accessed through SSL. Note the use of SERVER_NAME; because this is a complete site redirection, it's simplest to use the server's official name for itself.

The directive shown in the second solution causes all portions of the server's web space under http://myhost/normal/secure to be redirected to the SSL location rooted at https://myhost/. The use of HTTP_HOST rather than SERVER_NAME means that only the location and the scheme in the visitor's browser, not the server name.

Note that the paths to the SSL and non-SSL locations differ; if you want the paths to be the same except for the security, you can use something like the directives given in the third solution.

See Also

    [ Team LiB ] Previous Section Next Section