Restrict access to a location in Apache reverse proxy with TLS

September 4, 2020 

Ever had a case where you needed to use a name based Apache reverse proxy in front of some application server, while restring access to some proxied location at the same time? Here’s how to do it.

First define a virtual host:

<VirtualHost *:443>
    ServerName myserver.example.com

Set the request headers (you are of course using TLS, aren't you):

RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Port "443"

Proxy to some internal address, here to localhost port 8080:

ProxyRequests Off
ProxyPreserveHost On
ProxyPass http://127.0.0.1:8080/
ProxyPassReverse http://127.0.0.1:8080/

Restrict access to the host or networks you need to:

<Location "/my/location/">
 Require ip 10.0.0.0/8
</Location>

Note: this will work with Apache 2.4 and up. With older versions you can use the same idea.

Here is a complete configuration:

<VirtualHost *:443>
  ServerName myserver.example.com

  ## Vhost docroot
  DocumentRoot "/var/www/html"

  ## Directories, there should at least be a declaration for /var/www/html

  <Directory "/var/www/html">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Require all granted
  </Directory>

  ## Logging
  ErrorLog "/var/log/httpd/myserver_error_ssl.log"
  ServerSignature Off
  CustomLog "/var/log/httpd/myserver_access_ssl.log" combined

  ## Header rules
  Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"

  ## Request header rules
  RequestHeader set X-Forwarded-Proto "https"
  RequestHeader set X-Forwarded-Port "443"

  ## Proxy rules
  ProxyRequests Off
  ProxyPreserveHost On
  ProxyPass / http://127.0.0.1:8080/
  ProxyPassReverse / http://127.0.0.1:8080/

  ## Restrict accèss to /my/location
  <Location "/my/location/">
      Require ip 10.0.0.0/8
  </Location>

  ## SSL directives
  SSLEngine on
  SSLCertificateFile      "/etc/pki/tls/certs/my.crt"
  SSLCertificateKeyFile   "/etc/pki/tls/private/my.key"
</VirtualHost>
Samuli Seppänen
Petri Lammi
Author archive
menucross-circle