2011-11-29 129 views
18

我們都熟悉相對路徑:從http://www.domain.com/heyhttp://www.domain.com/hey/images/hello.jpg的鏈接到./images/hello.jpg的相對路徑。相對路徑,但對於端口?

問題:當你在http://www.domain.com/hey時,你如何聲明到http://www.domain.com:1234的相對路徑?

+0

我不認爲你可以。在這種情況下,端口實際上是域名的一部分。通過指定沒有端口的域名(不使用相對鏈接),您基本上提供了_different_域。 –

+1

另請參閱http://stackoverflow.com/q/6016120/60075 –

回答

20

這可以使用JavaScript通過設置window.location.port屬性來實現。

<a href="#" onclick="javascript:window.location.port=8080">go</a> 
+0

當然......但僅限於JavaScript。試着製作一個相對的StyleSheet路徑,例如 –

+0

不是100%確定問題適用於哪個上下文,但考慮到這個問題,我想你也可以從同一個端口爲CSS服務。那麼相對路徑將是相對的。 – peterp

+0

@Julien:猜猜我的背景假設是正確的。 – peterp

2

簡單的回答:不可能。 如果主機發生更改,則需要使用絕對路徑。

18

不能改變權威的任何部分:在相對URL(即主機端口一部分)。 查看RFC 3986section 5.2.2中描述的算法,瞭解如何解釋相對URL。需要注意的重要一點是,權限只是從基本URL或被解析的URL複製而來,並且權限的結構從不解釋。這意味着你不能改變它的任何部分,包括端口部分。

下面是來自RFC複製的僞代碼算法:

-- The URI reference is parsed into the five URI components 
    -- 
    (R.scheme, R.authority, R.path, R.query, R.fragment) = parse(R); 

    -- A non-strict parser may ignore a scheme in the reference 
    -- if it is identical to the base URI's scheme. 
    -- 
    if ((not strict) and (R.scheme == Base.scheme)) then 
    undefine(R.scheme); 
    endif; 

    if defined(R.scheme) then 
    T.scheme = R.scheme; 
    T.authority = R.authority; 
    T.path  = remove_dot_segments(R.path); 
    T.query  = R.query; 
    else 
    if defined(R.authority) then 
     T.authority = R.authority; 
     T.path  = remove_dot_segments(R.path); 
     T.query  = R.query; 
    else 
     if (R.path == "") then 
      T.path = Base.path; 
      if defined(R.query) then 
       T.query = R.query; 
      else 
       T.query = Base.query; 
      endif; 
     else 
      if (R.path starts-with "/") then 
       T.path = remove_dot_segments(R.path); 
      else 
       T.path = merge(Base.path, R.path); 
       T.path = remove_dot_segments(T.path); 
      endif; 
      T.query = R.query; 
     endif; 
     T.authority = Base.authority; 
    endif; 
    T.scheme = Base.scheme; 
    endif; 

    T.fragment = R.fragment; 
+0

感謝您在這個問題上的明確答案! –

-5

簡單的,你可以在href屬性寫:

/:port/[path/]file.ext