Sirius Wang
Sirius Wang

Reputation: 349

How to redirect web page from a specfic page in Sinatra?

In Sinatra, how to redirect a web page from a specific page?

require 'sinatra'

get "/A" do
    redirect '/B' 
end

get "/B" do 
    # if comes from A
    #     "IT COMES FROM A"    
    # else not from A
    #     "NOT FROM A , REDIRECT TO C"
    #     redirect '/C'
    # end
end

I want to learn how to do this?

Can I use JavaScript or HTML to do what I want to do?

Or, it must be done in Sinatra?


I tried this, but it keeps null ,

get "/B" do
    mypath = URI(request.referer || '').path
    if mypath == '/A'
      "hi i am b , u come from a"
    else
      "--#{request.referrer}--"
      redirect '/C'
  end
end

Upvotes: 0

Views: 400

Answers (2)

maddin2code
maddin2code

Reputation: 1354

The information of the HTTP referrer can be retrieved via:

request.referrer

But if it is a redirect initiated by the server, it doesn't count as the referrer to the target page. In short terms:

If /A redirects to /B because the server told the client the page moved (status 302), the referrer is not /A but the page which linked to /A or nothing, if /A got requested directly.

To answer the question: You have to use client side redirecting in order to get your idea working. Javascript can do the trick (placed on /A):

<script type="text/javascript">window.location = '/B';</script>

Upvotes: 4

Nirav Gandhi
Nirav Gandhi

Reputation: 2005

You can check for the referrer path to do so

URI(request.referrer).path

Better approach would be to pass some parameter in the query string and you can redirect based upon its presence.

Upvotes: 3

Related Questions