Created
August 20, 2019 16:14
-
-
Save mttjohnson/1ee38419f8dda8c61f5e7a31eed8a9c1 to your computer and use it in GitHub Desktop.
Nginx multi-conditional for whitelist of IP or user agent at a specific path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Set the $unauthorized_admin_ip flag if remote_addr is not on list of authorized IPs | |
map $remote_addr $unauthorized_admin_ip { | |
# All IPs are considered unauthorized by default | |
default 1; | |
"127.0.0.1" 0; | |
} | |
map $request_uri $unauthorized_admin_path { | |
# All paths are considered unauthorized by default and require some other | |
# means of authorization in order for the request to be accepted. | |
default 1; | |
~*^/\.well-known/.* 0; # Requests for Let's Encrypt will be granted authorization based on this path | |
} | |
server { | |
# ... | |
# Authorization Check - IP Address | |
if ($unauthorized_admin_ip) { | |
# Add failure value to combined authorization check variable | |
set $authorization_check 1; | |
} | |
# Authorization Check - IP Address | |
if ($unauthorized_admin_path) { | |
# Add failure value to combined authorization check variable | |
set $authorization_check "${authorization_check}2"; | |
} | |
# Determine if all Authorization Checks failed | |
if ($authorization_check = 12) { | |
# Authorization Checks failed at all points indicating | |
# there was no valid means that the request was able to | |
# be authorized and thus should be rejected. | |
return 444; | |
} | |
# ... | |
} | |
map $http_user_agent $block_user_agent { | |
default 1; | |
# Allow whitelisted User Agents | |
"~*Klaviyo" 0; | |
#~(Example1|Example2) 0; | |
} | |
map $request_uri $blocked_path { | |
# All paths are considered allowed by default | |
default 0; | |
~*^/media/catalog/product/(?!cache|placeholder) 1; # Requests for original media files should be blocked | |
} | |
server { | |
# ... | |
# Original Media Check - User Agent | |
if ($block_user_agent) { | |
# Add failure value to combined original media check variable | |
set $original_media_check 1; | |
} | |
# Original Media Check - Path | |
if ($blocked_path) { | |
# Add failure value to combined authorization check variable | |
set $original_media_check "${original_media_check}2"; | |
} | |
# Determine if all Original Media Checks failed | |
if ($original_media_check = 12) { | |
# Original Media Check failed at all points indicating | |
# there was no valid means that the request was able to | |
# be authorized and thus should be blocked. | |
return 403; | |
} | |
# ... | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment