How to get url after redirect - using Javascript?

It might be a little off the stadium, but a friend asked me about it and it bothered me. How do you determine the current path in your address bar if the server redirects all requests to a default file, say index.html.

Let's say you entered:

www.example.com/

      

And your server config will automatically redirect this request to

www.example.com/index.html

      

But the address in your url bar doesn't change! So how do you know using Javascript that the path on this url is index.html?

I looked at location.pathname but that only gave me /.

Any ideas?

+1


source to share


3 answers


The problem is that this is not a redirect. When you type 'www.example.com'

into your web browser, the browser generates an HTTP request, for example:

GET / HTTP/1.1
User-Agent: curl/7.16.3 (i686-pc-cygwin) libcurl/7.16.3 OpenSSL/
0.9.8h zlib/1.2.3 libssh2/0.15-CVS
Host: www.example.com
Accept: */*

      

Note that it asks for a document with a literal name /

. There are two possible answers on the server:

HTTP/1.1 200 OK
(more headers)

Content...

      



and

HTTP/1.1 301 Moved Permanently
Location: (location of redirect)
(more headers)

(Optional content)

      

In case # 2, you can get the redirect site as it really is a redirect. But in the case №1 server redirects: he sees the request for /

and instead serves the content for any of its index page (eg index.html

, index.php

, default.aspx

etc.) As far as your browser, it's just the content of the document /

. He doesn't know he is redirected.

+4


source


If the redirect is happening on the server, the browser is unaware of it and you cannot access the actual resource in javascript. For example, a servlet can "forward" another resource on the server.



If the server sends a redirect command to the browser and the browser asks for a new URL, the browser knows about it and you can get it.

+4


source


There is no way to do this, except that somehow the webserver file name is embedded in the document. As far as the browser is concerned, no index.html

, the page is simple /

.

+1


source







All Articles