RailsPlayground
How To Use RHTML without rails

First you want to ssh into the root dir that you want to server .rhtml files from and create a .htaccess with the following contents:


RewriteEngine Off
Options +FollowSymLinks +ExecCGI
AddHandler rubypage .rhtml
Action rubypage /cgi-bin/erb.cgi
DirectoryIndex index.rhtml index.html index.htm

next..


mkdir cgi-bin
vim cgi-bin/erb.cgi

and here’s what goes in erb.cgi:


#!/usr/local/bin/ruby
require 'time'
require 'erb'
include ERB::Util

time = Time.now.httpdate

HEADERS = <<-EOF
Date: #{ time }
Server: #{ ENV['SERVER_SOFTWARE'] }
Last-Modified: #{ time }
Content-Type: text/html

EOF

begin

  path = nil
  if (ENV['PATH_TRANSLATED'])
    path = ENV['PATH_TRANSLATED']
  else
    file_path = ENV['REDIRECT_URL'].include?(File.basename(__FILE__)) ? ENV['SCRIPT_URL'] : ENV['REDIRECT_URL']
    path = File.expand_path(ENV['DOCUMENT_ROOT'] + '/' + file_path)
    raise "Attempt to access invalid path: #{path}" unless path.index(ENV['DOCUMENT_ROOT']) == 0
  end
  erb = File.open(path) { |f| ERB.new(f.read) }
  print HEADERS + erb.result(binding)

rescue Exception

  print "Content-Type: text/html\n\n" 

  # what the customer sees
  print "<h1>Page Not Found</h1>" 

  # modify message variables
  ENV['SERVER_ADMIN'] = "admin@yourdomain.com" 

  # email message
  MESSAGE = " 
  From: Erb <admin@yourdomain.com>
  To: You <you@yourdomain.com>
  Subject: Error on YourDomain.com   

  ****Script Error****
  #{ $! }

  ****Backtrace****
  #{$!.backtrace.join("\n")}

  ****Environment****
  #{ENV.map { |key,val| key + ' = ' + val + "\n"} }" 

  # send the message
  require "net/smtp" 
  Net::SMTP.start('localhost', 25, 'yourdomain.com', 'admin+yourdomain.com', 'yourPassword', :login) do |smtp|
    smtp.send_message MESSAGE, 'admin@yourdomain.com', 'you@yourdomain.com'
  end

end

Make sure that the permissions on erb.cgi are 755 or it will not work. Not only does this script serve up your .rhtml pages, but it will notify you if there is a problem.

If you want to use a .rhtml page for your 404 errors just add one more line to your .htaccess file:


ErrorDocument 404 /404.rhtml