Redirecting HTTP to HTTPS without DNS or static IP

Posted on

A server stack is the collection of software that forms the operational infrastructure on a given machine. In a computing context, a stack is an ordered pile. A server stack is one type of solution stack — an ordered selection of software that makes it possible to complete a particular task. Like in this post about Redirecting HTTP to HTTPS without DNS or static IP was one problem in server stack that need for a solution. Below are some tips in manage your linux server when you find problem about linux, apache-2.4, web-server, ubuntu-20.04, .

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.

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
<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}"

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.

Leave a Reply

Your email address will not be published. Required fields are marked *