Last active
April 29, 2016 16:50
-
-
Save bdmorin/e2a8574192718f03b58f to your computer and use it in GitHub Desktop.
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.
This file contains 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
# explain what I'm trying to do | |
# Given base domain of abc.com | |
# 1) typical visitor will type in abc.com | |
# our SEO people want standardized www.abc.com all redirects are 301 | |
# 2) issues in our environment have template assets pointing to | |
# http://abc.com/skins/some.css | |
# 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 = abc.com) { | |
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 | |
# http://abc.com/ would be YNN | |
# http://abc.com/admin would be YYN | |
# http://abc.com/skin/ would be YNY | |
# http://www.abc.com/admin would be YYN | |
set $testNaked "${isNaked}${isAdmin}${isSkin}"; | |
if ($testNaked = YNN) { | |
rewrite ^(.*) http://www.abc.com$1 permanent; | |
} | |
#If it's admin and insecure, redirect to https | |
# http://abc.com/admin would have been previously redirected to http://www.abc.com | |
# http://www.abc.com/admin would be NY | |
# https://www.abc.com/admin would be YY | |
set $testAdmin "${isSecure}${isAdmin}"; | |
if ( $testAdmin = NY ) { | |
rewrite ^(.*) https://www.abc.com$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