1

I'm looking for the proper way to handle redirecting of insecure (via port 80) requests to secure (port 443) with Apache server config. I do not want to put this in my .htaccess file either.

Currently I have this in my httpd.conf file:

ServerName example.com
ServerAlias *.example.com

RewriteEngine On RewriteCond %{HTTP_HOST} ^(.+).example.com$ RewriteRule ^(.*)$ https://%1.example.com/$1 [R=302,L]

The goal is to do a wildcard (in subdomain and subfolder) redirect. To be specific, here are some major use cases:

 - http://subdomain.example.com to https://subdomain.example.com
 - http://example.com to https://www.example.com
 - http://www.example.com/contact/ to https://www.example.com/contact
 - http://subdomain.example.com/contact/ to https://subdomain.example.com/contact

In short, simply replacing http with https as long as two conditions meet:

  • The requested URI contains mydomain.com

  • The requested URI is not already secure (http traffic only)

I've tried numerous different methods but nothing seems to capture all variations of subdomains and subfolders, much to my surprise.

Any ideas? Thanks!

Tony D
  • 13

2 Answers2

0

A simple virtual host is the best way to catch all the HTTP requests. Then you cannot accidentally redirect HTTPS requests. Something like.

<VirtualHost *:80>
   ServerName example.com
   ServerAlias *.example.com

   # Redirect subdomains.
   RewriteEngine on
   RewriteCond %{HTTP_HOST} (\w+.example.com)
   RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]

   # Everything else to www.example.com preserving URI path
   Redirect 301 / https://www.example.com/
</VirtualHost
Unbeliever
  • 2,416
0

To redirect to HTTPS:

RewriteEngine On

RewriteCond %{HTTPS} off

RewriteRule ^ https:/ /%{HTTP_HOST}%{REQUEST_URI}

But you need to have a virtual host for ssl:

NameVirtualHost *:443

< VirtualHost *:443>

ServerName example.com

ServerAlias www.example.com

SSLEngine on

SSLCertificateFile    /etc/apache2/ssl/apache.crt

SSLCertificateKeyFile /etc/apache2/ssl/apache.key

< /VirtualHost>


Explaination of mod rewrite directives used

RewriteEngine On --- It will turn on mod_rewrite engine of apache server on

RewriteCond %{HTTPS} off ------

Will contain the text "on" if the connection is using SSL/TLS, or "off" otherwise. (This variable can be safely used regardless of whether or not mod_ssl is loaded). will evaluate to a true conditon if connection is not ssl/tls

RewriteRule ^ https:/ /%{HTTP_HOST}%{REQUEST_URI}

this is to form the url originally requested by client but in https