How do I SetEnv only for a specific IP in Apache?

Solution 1:

See the SetEnvIf directive, which defines environment variables based on attributes of the request, such as Remote_Addr (the IP address of the client making the request)...

SetEnvIf Remote_Addr ^192\.168\.0\. LOCAL_LAN=1

...or Server_Addr (the IP address of the server on which the request was received)...

SetEnvIf Server_Addr ^192\.168\.0\.1$ SITE_PROFILE=PRODUCTION
SetEnvIf Server_Addr ^192\.168\.0\.2$ SITE_PROFILE=DEVELOPMENT

Note that the second argument to SetEnvIf is a regular expression, so be extra mindful if you're tempted to use bare IPs, as a pattern like 192.168.1.1 (while looking a lot cleaner than escaping dots as I do above) will also end up matching 192.168.101.10.

UPDATE:

SetEnvIf can't access QUERY_STRING, but per the docs:-

See the RewriteCond directive of mod_rewrite for extra information on how to match your query string.

So something like...

RewriteCond %{REMOTE_ADDR} ^192\.168\.0\.
RewriteCond %{QUERY_STRING} (^|&)debug=
RewriteRule . - [E=LOCAL_LAN_AND_DEBUG:1]

Solution 2:

In Apache 2.4 you can set an environment variable for a single IP address or a whole subnet using CIDR notation. Eg.:

<If "-R '93.184.216.34'">
  SetEnv myvar1=example
</If>

<If "-R '93.184.216.0/24'">
  SetEnv myvar2=subnet
</If>

These can also be combined with logical operators inside the expression:

<If "-R '93.184.216.34' || 
     -R '192.0.32.0/24'">
  SetEnv myvar3=both
</If>