重定向不适用于本地主机上的sinatra

时间:2014-01-10 17:43:10

标签: ruby redis sinatra

get '/:shortcode' do
    @url = redis.get "links:#{params[:shortcode]}"
    if !@url.nil?
        redis.incr "clicks:#{params[:shortcode]}"
        redirect @url
    else
        redirect '/'
    end
end

这是片段,它与params有关,并检查它是否为nil?。有必要避免使用redis.incr创建随机密钥(如果它们不可用)。

问题是我一直被重定向到/。有什么想法吗?

[2014-01-10 18:37:50] INFO  WEBrick 1.3.1
[2014-01-10 18:37:50] INFO  ruby 2.0.0 (2013-06-27) [x86_64-linux]
== Sinatra/1.4.4 has taken the stage on 4567 for development with backup from WEBrick
[2014-01-10 18:37:50] INFO  WEBrick::HTTPServer#start: pid=13862 port=4567
127.0.0.1 - - [10/Jan/2014 18:37:55] "GET / HTTP/1.1" 200 1312 0.0038
localhost - - [10/Jan/2014:18:37:55 CET] "GET / HTTP/1.1" 200 1312
http://localhost:4567/ -> /
127.0.0.1 - - [10/Jan/2014 18:37:55] "GET /css/main.css HTTP/1.1" 304 - 0.0004
localhost - - [10/Jan/2014:18:37:55 CET] "GET /css/main.css HTTP/1.1" 304 0
http://localhost:4567/ -> /css/main.css
127.0.0.1 - - [10/Jan/2014 18:37:55] "GET /favicon.ico HTTP/1.1" 304 - 0.0010
localhost - - [10/Jan/2014:18:37:55 CET] "GET /favicon.ico HTTP/1.1" 304 0
- -> /favicon.ico
127.0.0.1 - - [10/Jan/2014 18:38:07] "POST / HTTP/1.1" 200 1449 0.0022
localhost - - [10/Jan/2014:18:38:07 CET] "POST / HTTP/1.1" 200 1449
http://localhost:4567/ -> /
127.0.0.1 - - [10/Jan/2014 18:38:14] "GET /br5z9 HTTP/1.1" 302 - 0.0010
localhost - - [10/Jan/2014:18:38:14 CET] "GET /br5z9 HTTP/1.1" 302 0
http://localhost:4567/ -> /br5z9
127.0.0.1 - - [10/Jan/2014 18:38:14] "GET /google.com HTTP/1.1" 302 - 0.0007
localhost - - [10/Jan/2014:18:38:14 CET] "GET /google.com HTTP/1.1" 302 0
http://localhost:4567/ -> /google.com
127.0.0.1 - - [10/Jan/2014 18:38:14] "GET / HTTP/1.1" 200 1312 0.0024
localhost - - [10/Jan/2014:18:38:14 CET] "GET / HTTP/1.1" 200 1312
http://localhost:4567/ -> /

编辑: 在此示例中,我在

处理的表单中添加了google.com
post '/' do
    if params[:url] and not params[:url].empty?
        @shortcode = random_string 5
        redis.multi do
            redis.set "links:#{@shortcode}", params[:url], :nx => true, :ex => 400
            redis.set "clicks:#{@shortcode}", "0", :nx => true, :ex => 400
        end
    end
    erb :index
end

硬编码网址的情况:

redirect @url更改为redirect 'google.com'即可。

127.0.0.1 - - [10/Jan/2014 18:55:32] "GET /google.com HTTP/1.1" 302 - 0.0008
localhost - - [10/Jan/2014:18:55:32 CET] "GET /google.com HTTP/1.1" 302 0
http://localhost:4567/ -> /google.com

1 个答案:

答案 0 :(得分:0)

重定向无法将google.com识别为外部链接,并尝试路由至http://localhost:4567/google.com

所以诀窍是使用http://google.com。我通过重写提交的字符串解决了这个问题。

unless params[:url] =~ /[a-zA-Z]+:\/\/.*/
    params[:url] = "http://#{params[:url]}"
end