Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS 

Multiple Rails Applications with lighttpd

# lighttpd.conf
$HTTP["url"] =~ "^/base_url_to_app1/" {
  server.document-root = "/path/to/app1/public/"
  alias.url = ( "/base_url_to_app1/" => "/path/to/app1/public/" )
  server.error-handler-404 = "/base_url_to_app1/dispatch.fcgi"
  fastcgi.server = (
    ".fcgi" => ( (
      "socket" => "/tmp/app1.socket",
      "bin-path" =>  "/path/to/app1/public/dispatch.fcgi",
    ) )
  )
}

$HTTP["url"] =~ "^/base_url_to_app2/" {
  # ...
}


# config/environment.rb
module ActionController
  class AbstractRequest
    alias_method :orig_rel_url_root, :relative_url_root
    def relative_url_root
      if (@env['SCRIPT_NAME'] && /\/dispatch\.(fcgi|rb|cgi)$/ =~ @env['SCRIPT_NAME'])
        @env["SCRIPT_NAME"].to_s.sub(/\/dispatch\.(fcgi|rb|cgi)$/, '')
      else
        orig_rel_url_root
      end
    end
  end
end

Very basic lighttpd configuration

The configuration of lighttpd is vast and complex. Here is a close to minimal configuration which allows for Perl and Ruby CGI.

server.document-root = "/opt/lighttpd/htdocs"

server.port = 3000

mimetype.assign = (
  ".html" => "text/html",
  ".txt" => "text/plain",
  ".jpg" => "image/jpeg",
  ".png" => "image/png"
)

static-file.exclude-extensions = ( ".rb", ".pl", ".fcgi", ".php", ".rb", "~", ".inc" )
index-file.names = ( "index.html" )
server.modules += ( "mod_cgi" )

cgi.assign = (  ".rb" => "/opt/ruby/bin/ruby",
                ".pl" => "/usr/bin/perl")

A tool to split log files by hostname

This script can be used to split a log file by the hostname in the request. It is designed for use with lighttpd virtual hosting, to prepare the log for Webalizer. It should be run with a cron job and CLI PHP.

<?php
// Copyright (C) 2006 Craig Spurrier
// Released under the terms of the MIT/expat license.

$serverip = "127.0.0.1"; //Set to your IP address or default hostname, so requests without hostnames can be sorted 
$log = file_get_contents("/var/log/lighttpd/access.log"); //Log location
$fh = fopen("/var/log/lighttpd/access.log", 'w'); //Clear the log file
fclose($fh);
$lines = explode ("\n", $log);
foreach ($lines as $line){
$parts = explode (" ", $line);
$hostname = strtolower($parts[1]);
if (substr($hostname, 0, 4) == 'www.'){$hostname = substr($hostname, 4);} //Treat www. as the same as the www-less version
if ($hostname == '-'){$hostname = $serverip;} //Set a hostname for request without hostnames
$fh = fopen("/var/log/lighttpd/users/$hostname.access.log", 'a'); //Add the entry to the log for that hostname. Make sure this script can write to this location.
fwrite($fh, "$line\n");
fclose($fh);
}
?>

lighttpd (or anything else) through apache2 proxy

<VirtualHost *:80>
  ServerAdmin        webmaster@inter.net
  ServerName         www.inter.net
  ProxyRequests      Off
  ProxyPreserveHost  On
  RewriteEngine      On
  RewriteRule        ^/(.*) http://127.0.0.1:3000/$1 [P,L]
  ProxyPassReverse   / http://127.0.0.1:3000/
</VirtualHost>

Apache2 proxy to local port

Apache as the receptionist, forwarding requests to and from an internal server (e.g. webrick or lighttpd).

<VirtualHost *>
        ServerName www.example.com
        ProxyPass / http://localhost:3000/
        ProxyPassReverse / http://localhost:3000/
        ProxyPreserveHost On
</VirtualHost>


Change 3000 to whatever port you need and make sure the internal server is set up to answer requests on that port (not port 80). The ProxyPreserveHost line is critical to keep all your URLs working correctly.

create lighttpd conf files for vhosting

Creates lighttpd conf files like suggested on http://blog.lighttpd.net/articles/2005/11/25/simplify-your-configfiles-with-includes
simply add include "incl-domains.conf" to your main lighttpd.conf file
#!/usr/bin/env ruby -w
#
# light_conf_editor.rb
#
# Created by yo on 25.12.05.
#
#
# Description
# Creates lighttpd conf files
#
# usage: light_conf_editor add || remove domainname username
# example: light_conf_editor add bigcurl.com yo
# example: light_conf_editor remove bigcurl.com yo

path_to_lighttpd_conf="/etc/lighttpd"

def remove_include_from_conf(domainname, username, path_to_lighttpd_conf)
  temp_file=""
  File.open("#{path_to_lighttpd_conf}/incl-domains.conf", "a+") unless FileTest.exist?("#{path_to_lighttpd_conf}/incl-domains.conf")
  File.open("#{path_to_lighttpd_conf}/incl-domains.conf", "r") do |file|
    file.each_line do |line| 
        temp_file.concat(line) unless line.include? "include \"domains/#{username}/#{domainname}.conf\""
    end
  end

  File.open("#{path_to_lighttpd_conf}/incl-domains.conf", "w") do |file|
    file.puts(temp_file)
  end

end

def remove_conf_from_folder(domainname, username, path_to_lighttpd_conf)
  File.delete("#{path_to_lighttpd_conf}/domains/#{username}/#{domainname}.conf")  if FileTest.exists?( "#{path_to_lighttpd_conf}/domains/#{username}/#{domainname}.conf" )

end

def add_new_conf_in_folder(include_template, domainname, username, path_to_lighttpd_conf)
  Dir.mkdir( "#{path_to_lighttpd_conf}/domains") unless FileTest.directory?( "#{path_to_lighttpd_conf}/domains/" )
  Dir.mkdir( "#{path_to_lighttpd_conf}/domains/#{username}/") unless FileTest.directory?( "#{path_to_lighttpd_conf}/domains/#{username}")

  aFile = File.new("#{path_to_lighttpd_conf}/domains/#{username}/#{domainname}.conf","w")
  aFile.puts(include_template)
  aFile.close
end

def add_new_include_in_conf(domainname, username, path_to_lighttpd_conf)
  File.open("#{path_to_lighttpd_conf}/incl-domains.conf", "a+") do |file|
    file.puts("include \"domains/#{username}/#{domainname}.conf\"")
  end
end

def show_usage
  print "usage: light_conf_editor add domainname username || remove domainname username\n"
end


if(ARGV.length < 3)
  show_usage
  exit(1)
end

domainname = ARGV[1]

username = ARGV[2]
if(ARGV[0]=="remove")
  remove_include_from_conf(domainname, username, path_to_lighttpd_conf)
  remove_conf_from_folder(domainname, username, path_to_lighttpd_conf)
end


if(ARGV[0]=="add")

  include_template = "$HTTP[\"host\"] =~ \"#{domainname}$\" {
  var.username   = \"#{username}\"
  var.servername = \"#{domainname}\"
  include \"incl-docroot.conf\"

  server.dir-listing        = \"enable\"
  dir-listing.hide-dotfiles = \"enable\"
  }"

  remove_include_from_conf(domainname, username, path_to_lighttpd_conf)
  remove_conf_from_folder(domainname, username, path_to_lighttpd_conf)

  add_new_conf_in_folder(include_template, domainname, username, path_to_lighttpd_conf)
  add_new_include_in_conf(domainname, username, path_to_lighttpd_conf)
  
end


Lighty redirect

Redirect http://www.jnewland.com and http:///blog.jnewland.com, both still indexed by Google, to http://jnewland.com. 'www' is so 1995 :)

$HTTP["host"] =~ "^(www.|blog.)" {
    url.redirect = (
        "^/(.*)" => "http://jnewland.com/$1",
        "" => "http://jnewland.com/",
        "/" => "http://jnewland.com/"
    )
}

Feedburner Redirect

Redirect everyone except the feedburner spider to FeedBurner's cached version.

$HTTP["host"] =~ "^(www.|blog.)?jnewland.com" {
    $HTTP["useragent"] !~ "FeedBurner" {
        url.redirect = (
            "/xml/rss20/feed.xml" => "http://feeds.feedburner.com/jnewlandcom"
        )
    }
}

Lighttpd Rails Script with SSL options

#!/usr/bin/env ruby

require 'optparse'
require 'fileutils'
require 'tmpdir'

OPTIONS = {
  :port        => 3000,
  :ip          => "0.0.0.0",
  :daemon      => false,
  :environment => "development",
  :app_name    => Process::pid.to_s,
  :max_procs   => 3,
  :min_procs   => 1,
  :ssl         => false,
  :pemfile     => "server.pem",
}

ARGV.options do |opts|
  script_name = File.basename($0)
  opts.banner = "Usage: ruby #{script_name} [options]"

  opts.separator ""

  opts.on("-p", "--port=port", Integer,
          "Runs Rails on the specified port.",
          "Default: 8000") { |OPTIONS[:port]| }
  opts.on("-b", "--binding=ip", String,
          "Binds Rails to the specified ip.",
          "Default: 0.0.0.0") { |OPTIONS[:ip]| }
  opts.on("-e", "--environment=name", String,
          "Specifies the environment to run this server under (test/development/production).",
          "Default: development") { |OPTIONS[:environment]| }
  opts.on("-a", "--app-name=name", String,
          "Specifies the application name.",
          "Default: process_id") { |OPTIONS[:app_name]| }
  opts.on("-d", "--daemon",
          "Make lighttpd / Rails run as a Daemon (only works if fork is available -- meaning on *nix)."
          ) { OPTIONS[:daemon] = true }
  opts.on("-n", "--min-procs=number", Integer,
          "Minimum number of FastCGI processes allowed.",
          "Default: 1") { |OPTIONS[:min_procs]| }
  opts.on("-m", "--max-procs=number", Integer,
          "Maximum number of FastCGI processes allowed.",
          "Default: 3") { |OPTIONS[:max_procs]| }
  opts.on("-l", "--enable-ssl",
          "Enable SSL."
          ) { OPTIONS[:ssl] = true }
  opts.on("-f", "--pemfile=pemfile", String,
          "path to the PEM file for SSL support."
          ) { |OPTIONS[:pemfile]| }
  
  opts.separator ""

  opts.on("-h", "--help",
          "Show this help message.") { puts opts; exit }

  opts.parse!

end

ENV["RAILS_ENV"] = OPTIONS[:environment]
RAILS_ROOT = Dir.pwd + "/./"
TMP_DIR = Dir.tmpdir
LIGHTTPD_CONF_FILE = TMP_DIR + "/lighttpd.#{OPTIONS[:app_name]}.conf"

conf = DATA.read
conf.gsub!('__PORT__', OPTIONS[:port].to_s)
conf.gsub!('__BINDING__', OPTIONS[:ip])
conf.gsub!('__RAILS_ROOT__', File.expand_path(RAILS_ROOT))
conf.gsub!('__APP_NAME__', OPTIONS[:app_name])
conf.gsub!('__MIN_PROCS__', OPTIONS[:min_procs].to_s)
conf.gsub!('__MAX_PROCS__', OPTIONS[:max_procs].to_s)
conf.gsub!('__RAILS_ENV__', ENV['RAILS_ENV'])
conf.gsub!('__TMP_DIR__', TMP_DIR)
conf.gsub!('__SSL__', OPTIONS[:ssl] ? "enable" : "disable")
conf.gsub!('__PEMFILE__', OPTIONS[:pemfile])
File.open(LIGHTTPD_CONF_FILE, "w") { |output| output.write(conf) }

CMD = "/usr/sbin/lighttpd -f #{LIGHTTPD_CONF_FILE}"
CMD << " -D" if not OPTIONS[:daemon]

puts "=> Rails application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}"
puts "=> Ctrl-C to shutdown server; call with --help for options" if not OPTIONS[:daemon]

puts CMD
`#{CMD}`

FileUtils.rm Dir.glob(TMP_DIR + "/lighttpd.#{OPTIONS[:app_name]}.*") if not OPTIONS[:daemon]

__END__
server.port                = __PORT__
server.bind                = "__BINDING__"
server.pid-file             = "__TMP_DIR__/lighttpd.__APP_NAME__.pid"
server.max-keep-alive-requests = 4
server.max-keep-alive-idle = 4

ssl.engine = "__SSL__"
ssl.pemfile = "__PEMFILE__"

#server.event-handler = "freebsd-kqueue"

server.modules = ( "mod_rewrite", "mod_redirect", "mod_access", "mod_fastcgi", "mod_accesslog" )
server.document-root        = "__RAILS_ROOT__/public/"
server.indexfiles           = ( "index.html" ,"dispatch.fcgi")
accesslog.filename          = "__RAILS_ROOT__/log/lighttpd.__RAILS_ENV__.access.log"
server.errorlog             = "__RAILS_ROOT__/log/lighttpd.__RAILS_ENV__.error.log"
server.error-handler-404 = "/dispatch.fcgi"

#### fastcgi module

## read fastcgi.txt for more info
fastcgi.server =  (
                   ".fcgi" => (
                               "__APP_NAME__" => (
                                                  "socket" => "__TMP_DIR__/lighttpd.__APP_NAME__.fcgi.socket",
                                                  "bin-path" => "__RAILS_ROOT__/public/dispatch.fcgi",
                                                  "min-procs" => __MIN_PROCS__,
                                                  "max_procs" => __MAX_PROCS__
                                                  )
                               )
                   )


mimetype.assign             = (
                               ".rpm"          =>      "application/x-rpm",
                               ".pdf"          =>      "application/pdf",
                               ".sig"          =>      "application/pgp-signature",
                               ".spl"          =>      "application/futuresplash",
                               ".class"        =>      "application/octet-stream",
                               ".ps"           =>      "application/postscript",
                               ".torrent"      =>      "application/x-bittorrent",
                               ".dvi"          =>      "application/x-dvi",
                               ".gz"           =>      "application/x-gzip",
                               ".pac"          =>      "application/x-ns-proxy-autoconfig",
                               ".swf"          =>      "application/x-shockwave-flash",
                               ".tar.gz"       =>      "application/x-tgz",
                               ".tgz"          =>      "application/x-tgz",
                               ".tar"          =>      "application/x-tar",
                               ".zip"          =>      "application/zip",
                               ".mp3"          =>      "audio/mpeg",
                               ".m3u"          =>      "audio/x-mpegurl",
                               ".wma"          =>      "audio/x-ms-wma",
                               ".wax"          =>      "audio/x-ms-wax",
                               ".ogg"          =>      "audio/x-wav",
                               ".wav"          =>      "audio/x-wav",
                               ".gif"          =>      "image/gif",
                               ".jpg"          =>      "image/jpeg",
                               ".jpeg"         =>      "image/jpeg",
                               ".png"          =>      "image/png",
                               ".xbm"          =>      "image/x-xbitmap",
                               ".xpm"          =>      "image/x-xpixmap",
                               ".xwd"          =>      "image/x-xwindowdump",
                               ".css"          =>      "text/css",
                               ".html"         =>      "text/html",
                               ".htm"          =>      "text/html",
                               ".js"           =>      "text/javascript",
                               ".asc"          =>      "text/plain",
                               ".c"            =>      "text/plain",
                               ".conf"         =>      "text/plain",
                               ".text"         =>      "text/plain",
                               ".txt"          =>      "text/plain",
                               ".dtd"          =>      "text/xml",
                               ".xml"          =>      "text/xml",
                               ".mpeg"         =>      "video/mpeg",
                               ".mpg"          =>      "video/mpeg",
                               ".mov"          =>      "video/quicktime",
                               ".qt"           =>      "video/quicktime",
                               ".avi"          =>      "video/x-msvideo",
                               ".asf"          =>      "video/x-ms-asf",
                               ".asx"          =>      "video/x-ms-asf",
                               ".wmv"          =>      "video/x-ms-wmv",
                               ".bz2"          =>      "application/x-bzip",
                               ".tbz"          =>      "application/x-bzip-compressed-tar",
                               ".tar.bz2"      =>      "application/x-bzip-compressed-tar"
                               )

regex matching in lighttpd configs

Match the host name and rewrite paths like /images to blah.com/images:

$HTTP["host"] =~ "^.*\.([^.]+\.[^.:]+)(:|^)" {
  url.rewrite = ( "^/images/(.*)" => "/%1/images/$1",
                 "^/files/(.*)" => "/%1/files/$1",
 "^/$" => "index.html", "^([^.]+)$" => "$1.html")
}


provided by Dreamer3 and annotated here so I can quit bugging him about it.
« Newer Snippets
Older Snippets »
Showing 1-10 of 21 total  RSS