浏览器会忽略URL中的斜杠吗?

时间:2014-12-21 09:15:55

标签: url browser uri

我注意到Chrome和Firefox都忽略了网址中字词之间的斜杠。

因此,github.com/octocat/hello-world似乎等同于github.com//////octocat////hello-world

我正在编写一个解析URL并检索其中一部分的应用程序,并且由于这种行为,我能够在不修改代码的情况下返回原始URL,在我的情况下相当方便。我不知道依靠这个怪癖是不是一个好主意。

4 个答案:

答案 0 :(得分:18)

路径分隔符根据this定义为单斜杠。 (搜索路径组件

请注意,浏览器通常不会修改网址。浏览器could append a / at the end of a URL,但在您的情况下,带有额外斜杠的URL只是在请求中发送,因此 服务器忽略斜杠。

另外,请看一下:

即使这种行为对您来说很方便,也是generally not recommended。此外,缓存也可能会受到影响(source)

  

由于您的浏览器和服务器都缓存单个页面(根据其缓存设置),通过稍微不同的URI多次请求同一文件可能会影响缓存(取决于服务器和客户端实现)。

答案 1 :(得分:9)

空路径段根据specification生效:

path          = path-abempty    ; begins with "/" or is empty
              / path-absolute   ; begins with "/" but not "//"
              / path-noscheme   ; begins with a non-colon segment
              / path-rootless   ; begins with a segment
              / path-empty      ; zero characters

path-abempty  = *( "/" segment )
path-absolute = "/" [ segment-nz *( "/" segment ) ]
path-noscheme = segment-nz-nc *( "/" segment )
path-rootless = segment-nz *( "/" segment )
path-empty    = 0<pchar>

segment       = *pchar
segment-nz    = 1*pchar
segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" )
              ; non-zero-length segment without any colon ":"

pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"

在后一个URI https://github.com//////octocat////hello-world中,路径//////octocat////hello-world将由以下内容组成:

  • //////octocat////hello-world path-abempty
    • / segment
    • / segment
    • / segment
    • / segment
    • / segment
    • /octocat segment-nz
    • / segment
    • / segment
    • / segment
    • /hello-world segment-nz

删除这些空路径段将构成完全不同的URI。服务器如何处理这些空路径段是一个完全不同的问题。

答案 2 :(得分:6)

实际上浏览器不会忽略它们,它们会在HTTP请求中将它们传递给Web服务器。它可能决定忽略它们的服务器,但技术上乘以斜线会产生不同的URL。

W3.org指定网址的路径部分由&#34;路径段&#34;组成,由/分隔,路径段由零个或多个&#34; URL单元组成&# 34; (字符)除了/?,因此允许使用空路径段,这是复制斜杠时的结果。

有关详细信息,请参阅http://www.w3.org/TR/url-1/

答案 3 :(得分:3)

实际上,浏览器不会忽略网址之间的斜杠。

如果您在(客户端)JavaScript中使用document.URL,则会获得带有重复“///”的网址。

同样在(服务器端)PHP中,当使用$_SERVER['REQUEST_URI']时,您将获得带有重复“///”的URL。

服务器(例如Apache)实际上重定向到没有URL的正确页面。在Apache中,您可以在.htaccess文件中编写规则,以便不重定向到///被忽略的页面。

相关问题