Skip to content

Instantly share code, notes, and snippets.

@peterjaap
Last active February 7, 2019 06:15
Show Gist options
  • Save peterjaap/617a894464d4358d49fe to your computer and use it in GitHub Desktop.
Save peterjaap/617a894464d4358d49fe to your computer and use it in GitHub Desktop.
Conditionally switching HTTPS for different domains in nginx
# Unfortunately, we are not able to set the server {} due to hosting limitations.
# So we don't care that if is evil. We love if. Hooray for if!
# We want to redirect HTTP traffic to HTTPS, but only for two of our domains (the other domains still only use HTTP)
# set a var to 0 so when after a redirect, the existing connection is still used,
# the flag is set back to 0 instead of remembering its previosly set value
set $http 0;
# give the var a random value (in this case 1) when the if statement is true
if ($scheme = http) {
set $http 1;
}
# append another random value when the http_host matches to the domain
# you want to enable https redirect for
if ($http_host = www.yourssldomain.nl) {
set $http "${http}1";
}
if ($http_host = www.yourotherssldomain.nl) {
set $http "${http}1";
}
# check the value whether both if statements are true and redirect to https version
if ($http = 11) {
return 301 https://$http_host$request_uri;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment