Search code examples
asp.nethyperlinkprefix

Different between link prefix "~/" and "/"


Sometime we need to put / or ~/ as the suffix in order to make refer to the root

<script type="text/javascript" src="/scripts/jquery-1.5.1.min.js"></script>
<link href="~/Styles/MasterPage.css" rel="stylesheet" type="text/css" />

This is what i know from Phill

~/ is not valid unless you have a runat attribute on your control/element. '/' by itself specifies to the browser to look from the root directory, so if you link to '/css/main.css' from www.mysite.com/product/view.aspx it will look for the css file in www.mysite.com/css/main.css. When you use '~/' with runat-server, it will work out the path to the directory at runtime, so in the same example with '~/css/main.css' the rendered url will look like '../css/main.css' because it needs to drop the directory back 1 before finding the directory 'css'. (hope that makes sense) – Phill How to include jquery in masterpage header without path problems?

but as i has tried, even i use / firefox still refer to ../../ instead of static path. also, I don't know it clearly how to use it correctly , which one use on which situation.


Solution

  • ~/ refers to virtual directory application root where as "/" refers to site roots eg if you have site that in http://www.example.com/ and which has http://www.example.com/foo where folder "foo" configured as virtual directory application in IIS a page in http://www.example.com/foo/foo.aspx will resolve ~/ as relative to virtual directory application root directory which is http://www.example.com/foo but "/" will still resolve to site root which is http://www.example.com/