This post shows how to password protect a website with an Apache .htaccess file, but still allow access for a particular user-agent.
Allowing a process or browser access by their user-agent isn’t really the most ideal solution: it’s far better to allow access by IP address, but sometimes it’s necessary if the IP address of the remote process/browser may change but the user-agent will remain the same.
Ideally this method shouldn’t be used for something requiring high levels of security, but it can be useful if you need to, like I do, allow access to a payment provider’s callback to let your website know the payment has succesfully been processed.
Add this to your .htaccess file, see below for what you need to substitute:
SetEnvIfNoCase User-Agent [UserAgentName] AllowedUserAgent AuthUserFile /path/to/.htpasswd AuthName "Restricted Access" AuthType Basic Order deny,allow Deny from all Require user [username] Allow from env=AllowedUserAgent Satisfy Any
Change [UserAgentName] to the name of the user agent. You can use pattern matching, so .*google.* would match a user agent with “google” anywhere in it.
Change /path/to/.htpasswd to the actual location of your password file.
Change [username] to the username(s) you want to allow access.
Real world example
I needed to test PxPay by Direct Payment Solutions (DPS), which uses what they call “fail-proof result notification (FPRN)”. They specifically note that there should not be any conditional logic based on the originating IP address when the payment notification is made.
I can’t really make any assumptions about the user-agent, but it always came through as PXL1 when I tested it, so this is what my .htaccess file looked like:
SetEnvIfNoCase User-Agent PXL1 DPS AuthUserFile /path/to/.htpasswd AuthName "Restricted Access" AuthType Basic Order deny,allow Deny from all Require user [username] Allow from env=DPS Satisfy Any
I have a number of other recipes and tips for password, IP address, etc protection with .htaccess in my Apache .htaccess recipes, tips and tricks post, so be sure to check them out.