Teddy Hwang
Teddy Hwang

Reputation: 131

Redirecting everyone who doesn't have a specific user agent in .htaccess?

I've seen people redirect iPhone users by using this:

RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteCond %{REQUEST_URI} !^/my-iPhone-site/ 
RewriteRule .* /my-iPhone-site/ [R]

But how could I make a webpage only accessible with a specific user agent? Instead of blacklisting iPhones, I would like to whitelist them, for example.

Let me know!

Upvotes: 1

Views: 1155

Answers (2)

MrWhite
MrWhite

Reputation: 45968

To only allow requests to /my-iPhone-site/... from user-agents that contain iPhone then you could do something like the following using mod_rewrite in .htaccess (near the top):

RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} !iPhone
RewriteRule ^my-iPhone-site/ - [F]

This blocks (403 Forbidden) any user that tries to access /my-iPhone-site/... that does not contain iPhone in the user-agent string.

The ! prefix on the CondPattern negates the regex. So, in this example, it is successful when the HTTP_USER_AGENT server variable does not contain the string "iPhone".

If you wanted to redirect such users instead then change the RewriteRule to read:

RewriteRule ^my-iPhone-site/ /non-iPhone-site/ [R,L]

NB: You should use the L flag when redirecting, otherwise processing continues through your file.

Upvotes: 1

Teddy Hwang
Teddy Hwang

Reputation: 131

@MrWhite's answer didn't work for some reason, but this was how I figured it out.

 SetEnvIf User-Agent .*iPhone* iPhone

 Order deny,allow
 Deny from all
 Allow from env=iPhone

This will take all non iPhone users to 403.

Upvotes: 2

Related Questions