Skip to content

Instantly share code, notes, and snippets.

@dv
Created January 20, 2015 11:48
Show Gist options
  • Save dv/2db961954c8297d4f4d1 to your computer and use it in GitHub Desktop.
Save dv/2db961954c8297d4f4d1 to your computer and use it in GitHub Desktop.
Forcing nginx into submission (aka running nginx using dynamically compiled config files)
require 'rubygems'
require 'erb'
# Nginx needs its config files to contain absolute paths, so
# we need to compile them to set the correct paths.
def expand(filename)
full_path = File.expand_path(File.dirname(__FILE__)) # "~/Users/david/poetry/sslqsquire/canary"
File.join(full_path, filename)
end
def compile(filename)
unless filename.start_with? "/"
filename = expand(filename)
end
contents = File.read(filename)
ERB.new(contents).result(binding)
end
def indent(content)
content.split("\n").map{|s| " #{s}"}.join("\n")
end
def block(name)
stdout = $stdout
$stdout = StringIO.new
output = ""
begin
output << yield.to_s
ensure
output = $stdout.string + output
$stdout = stdout
end
"#{name} {\n" +
"#{indent(output)}\n" +
"}\n"
end
def render_site(path)
block "http" do
block "server" do
puts "root " + expand('nginx/webroot') + ";"
compile(path)
end
end
end
config_file = expand("tmp/nginx.conf")
# Generate config file
File.open config_file, "w" do |conf|
conf.puts "# Generated at #{Time.now}"
# Compile the main config file
conf << compile("nginx/nginx.conf.erb")
# Compile the different sites
Dir.glob(expand("sites") + "/*.erb") do |erb_file|
conf << "# #{erb_file}\n"
conf << render_site(erb_file)
conf << "\n\n"
end
end
`nginx -c #{config_file}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment