From: Simon Strandgaard Date: 2004-12-03T04:28:39+09:00 Subject: Re: [WEBrick] howto rewrite url On Tue, 30 Nov 2004 08:12:29 +0900, GOTOU Yuuzou wrote: > In message , > `Simon Strandgaard ' wrote: > > I am curious to if its possible to rename the url of the > > request "on the server".. so that user-agent never knows about that > > redirecting occured? > > It isn't possible yet. First, I'd like to make it possible > in 1.9. > I have investigated how to rewrite urls.. and have made this code. It rewrites urls from "show-all.html" to "show.cgi?all". And from "show-abcd.html" to "show.cgi?first=a;last=d". I hope its usable. require "webrick" class WEBrick::HTTPServer alias :old_initialize :initialize alias :old_service :service def initialize(config={}, default=WEBrick::Config::HTTP) old_initialize(config, default) @rewrite_rules = [] end def rewrite(pattern, subst) @logger.debug("rewrite rule %s -> %s." % [pattern.inspect, subst]) @rewrite_rules << [pattern, subst] end def service(req, res) path = req.path @rewrite_rules.each do |pattern, subst| if pattern =~ path new_path = path.gsub(pattern, subst) @logger.debug("rewrote url from %s to %s" % [path, new_path]) req.instance_variable_set("@path", new_path) # TODO: req.query = reload break end end old_service(req, res) end end class PageServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET(req, res) ary = [ ["path", req.path], ["path_info", req.path_info], ["request_uri", req.request_uri.inspect], ["unparsed_uri", req.unparsed_uri.inspect], ["query", req.query.inspect], ["query_string", req.query_string.inspect] ] rows = ary.map{|line| cells = line.map{|cell| "#{cell}"}.join "#{cells}" }.join str = "#{rows}
" res.body = "#{str}" res['Content-Type'] = "text/html; charset=iso-8859-1" end end if $0 == __FILE__ s = WEBrick::HTTPServer.new( :Port => 10080, :Logger => WEBrick::Log.new($stderr, WEBrick::Log::DEBUG), :AccessLog => [ [ $stderr, WEBrick::AccessLog::COMMON_LOG_FORMAT ], [ $stderr, WEBrick::AccessLog::REFERER_LOG_FORMAT ], [ $stderr, WEBrick::AccessLog::AGENT_LOG_FORMAT ], ] ) s.mount("/", PageServlet) s.mount("/show.cgi", PageServlet) s.rewrite(/show-all.html(?=$|\?)/, "show.cgi?all") s.rewrite(/show-abcd.html$/, "show.cgi?first=a;last=d") trap(:INT) do #fork{ s.shutdown } exit! end s.start end