Cuong Huynh
Published in

Cuong Huynh

Combine Apache’s HTTP authentication with X-Forwarded-For IP whitelisting in a reverse proxy Loadbalancer

If you want to protect a page or an entire website with HTTP authentication, but also want to whitelist a few fixed IPs (for instance: office or VPN IPs), you can combine both authentication mechanisms in Apache 2.4 via .htaccess files.

The full example goes like this.

.htaccess

Request Deny

Require all denied

Set deny all requests as default.

Basic Auth

AuthName "Restricted Area"
AuthType Basic
AuthBasicProvider file
AuthUserFile /path/to/your/.htpasswd

Use Basic authentication.

Require valid-user

Show password prompt.

IP Whitelisting

Normal IP whitelist

# Normal whitelist would just add Allow directives
Require ip 12.34.56.7
Require ip 12.34.56.8

Behind a reverse proxy, load balancer or a CDN, the IP available in logs is the load balancer / reverse proxy IP. Not the client IP. The client IP information can be found in X-Forwarded-For field

# Allow from an IP in the X-Forwarded-For header
SetEnvIF X-Forwarded-For "12.34.56.7" AllowIP
SetEnvIF X-Forwarded-For "12.34.56.8" AllowIP
Require env AllowIP

References:
https://ma.ttias.be/apache-http-authentication-with-x-forwarded-for-ip-whitelisting-in-varnish/#ip-whitelisting-with-x-forwarded-for
https://vfac.fr/blog/block-allow-ip-with-apache-2
https://httpd.apache.org/docs/2.4/howto/access.html

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Cuong Huynh

Cuong Huynh

24 Followers

I’m a web developer from Saigon, Vietnam. I’ve been making website for about 6 years. My focus right now is Express, Reactjs, Nextjs, Hasura, Serverless.