2

I've setup web servers in the past, but now I'm working on an embedded Linux project that is a bit different. I need the embedded Linux device to

  • run an Apache server
  • support DHCP
  • not require any DNS setup
  • (needs to basically be plug-n-play and idiot proof).

I'm a bit unsure how to do an HTTP to HTTPS redirect. What makes it tough is that I will not know the DNS or the IP. Is there a way for the mod-rewrite to dynamically detect the current IP and redirect to HTTP like this:

RewriteRule ^(.*)$ https://[(currentDHCPIPAddress)/$1 [L,R=301]

Most of the traffic will be from the internal LAN, so I can't do some sort of firewall magic.

If anyone else has any ideas to achieve this I would love to hear suggestions. It's a bit different than the way you'd ever want to setup most servers, so it has stumped me for the moment and most docs don't prepare you for this sort of use case.

Esa Jokinen
  • 43,252
  • 2
  • 75
  • 122
mberna
  • 123
  • 3
  • Another issue you will face is TLS certificate, and there isn't a way you can generate a valid certificate for your https connection. – Tero Kilkanen Apr 04 '21 at 07:28
  • Yeah, I was expecting the cert name mismatch, but it can be accepted in the browser fairly easily, so I'm not super concerned about it. – mberna Apr 04 '21 at 15:38
  • But, will requests arrive with a name or with an IP in the Host header? You need to know that before you decide. If it's names just use the variable %{HTTP_HOST} in the destination. – ezra-s Apr 06 '21 at 13:58

1 Answers1

4

This is a simple redirection, so let's first avoid using mod_rewrite and use mod_alias Redirect, instead.

If the Redirect directive is used within a <Location> or <LocationMatch> section with the URL-path omitted, then the URL parameter will be interpreted using expression syntax.

With the expression syntax you can use variables, and %{HTTP_HOST} contains whatever there is in the Host: header i.e. the hostname on the address bar of the browser, whether it is a DNS name or an IP address. That is exactly what you were looking for.

Let's put this together. Your default (first or only) name-based virtual host could have:

NameVirtualHost *:80
<VirtualHost *:80> 
    <Location "/">
        Redirect "https://%{HTTP_HOST}%{REQUEST_URI}"
    </Location>
</VirtualHost>

This will make any HTTP requests on port 80 redirect to its HTTPS equivalent, unless there is a matching name-based virtual host configured differently.

Esa Jokinen
  • 43,252
  • 2
  • 75
  • 122
  • 1
    Thanks Esa. Worked perfectly. Couldn't find this sort of thing explained in any documents. Hopefully others wondering the same can find your answer now also. – mberna Apr 04 '21 at 15:48