April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Categories

April 2025
M T W T F S S
 123456
78910111213
14151617181920
21222324252627
282930  

Proxying from Apache HTTPS to some backend server that only speaks HTTP

Proxying from Apache HTTPS to some backend server that only speaks HTTP

Here’s a use case: You want to run an application server that only speaks HTTP, but securely, over HTTPS. The problem is that the application server won’t know that it’s being accessed via HTTPS, so any URLs and redirects it generates might point to HTTP. Here’s an example virtual host entry that takes care of that by rewriting the header.

You need Apache, mod_proxy and mod_headers.


ServerName foo.bar.example.com

SSLEngine on
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
Header edit Location “^http:(.*)$” “https:$1”

PassengerEnabled off
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/

DocumentRoot /var/www/foo/bar

AllowOverride none
Options -MultiViews


The magical line is the one with “Header edit…”. This makes sure any request your app server would have sent to HTTP are rewritten to HTTPS.

Header edit Location ^http://(yourdomain.com/sslpath.*) https://$1

httpd.conf

LoadModule ext_filter_module modules/mod_ext_filter.so

RewriteEngine on

#1
RewriteCond %{REQUEST_URI} ^/gw/192\.168\.0\.[0-9]{1,3}/
RewriteRule ^/gw/(.*) /gw/http://$1 [R,NS,L]

#2
RewriteCond %{REQUEST_FILENAME} !/\.ht.* [NC]
RewriteCond %{REQUEST_URI} ^/gw/https?[:/]+192\.168\.0\.[0-9]{1,3}/
RewriteRule ^/gw/(https?)[:/]+(.*) $1://$2 [P,L,NS]

#3
Header edit Location ^(https?)[:/]+(.*) /gw/$1://$2

#4
ExtFilterDefine fixurl mode=output cmd=”/bin/bash /var/www/bin/url_rewrite.sh”
SetOutputFilter fixurl

#!/bin/bash

host=$(echo ${DOCUMENT_URI} | sed -e ‘s|^/gw/\(https\?\)[:/]\+\([^/]*\)/.*|/gw/\1://\2/|g’)

/bin/sed \
-e “s%\(href\|src\|action\)=\”/\([^\” <>\n]*\)\”%\1=\”${host}\2\”%g” \
-e “s%\(url: *[‘\”]\)/\([^’\”]*[‘\”]\)%\1${host}\2%g” \
-e “s%\”\(https\?\)[:/]\+\(192\.168\.0\.[0-9]\{1,3\}\)/%\”http://${HTTP_HOST}/gw/\1://\2/%g” \
-e “s%localhost/%${HTTP_HOST}${host}%g”

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>