Skip to content

Instantly share code, notes, and snippets.

Last active April 29, 2016 16:50
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
My solution for setting multiple conditionals based on several variables in nginx. nginx doesn't allow for nested if statements, if/else, or any advanced logic, so this is what I came up with.
# explain what I'm trying to do
# Given base domain of
# 1) typical visitor will type in
# our SEO people want standardized all redirects are 301
# 2) issues in our environment have template assets pointing to
# This makes the browser redirect nearly 15 times, not good.
# 3) We want only the admin area to be https. Due to insecure pixels and other assets
# the rest of the website wouldn't load if it was all https.
#Set all my tracking variables to N for false; this is string, not boolean.
set $isSecure N;
set $isSkin N;
set $isAdmin N;
set $isNaked N;
# Set to Y if the client is already in https
if ($https = on) {
set $isSecure "Y";
# Set to Y if the request is part of the assets we don't want to redirect
if ($request_uri ~ ".*/(skin|templates)/.*") {
set $isSkin "Y";
# Set to Y if we need to redirect for SEO purposes; should not redirect template assets
if ($http_host = {
set $isNaked "Y";
# If the client is in the /admin area then make the connection secure
if ($request_uri ~ "^/(framework/)?admin") {
set $isAdmin "Y";
# If it's a naked domain and NOT admin, and NOT skins, then redirect to www for SEO
# would be YNN
# would be YYN
# would be YNY
# would be YYN
set $testNaked "${isNaked}${isAdmin}${isSkin}";
if ($testNaked = YNN) {
rewrite ^(.*)$1 permanent;
#If it's admin and insecure, redirect to https
# would have been previously redirected to
# would be NY
# would be YY
set $testAdmin "${isSecure}${isAdmin}";
if ( $testAdmin = NY ) {
rewrite ^(.*)$1 permanent;
# I don't need to test for anything else as the logic handles itself from here.
# If I need to add more tests I can just concat the other tests and test against that.
# Hope this helps, if you have a better way; I'd love to hear it!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment