Relative URLs

When we use links in our master pages, we need to consider that left as they are, they will only work for pages in the same folder as our masterpage.

If we create a new folder, and place a new page based on our masterpage in it, its links will be relative to the position of the new page, not of the position of the masterpage.

To resolve this problem, we need to tell the links on the masterpage that they should be created by the server (by adding a runat="server" attribute and value) when the page is loaded, and provide a URL relative to the root of the website, by adding a tilde ~ and the full path from the root.

The example below shows a standard link

<a href="Default.aspx">Home</a>

The next example is a modified link which will work for pages based on the masterpage, irrespective of location in a folder structure.

<a href="~/Default.aspx" runat="server">Home</a>

Remember, it is not just hyperlinks on the master page that need to be made relative, the source for images and any other media should also be made relative in the same way.

The <head> element

Things are slightly different when referring to items in the <head> tag. We need to specify that the entire <head> be managed by the server, this will then enable us to specify relative links to our stylesheets etc as above, although runat="server" only needs to be added to the head opening tag, e.g:

<head runat="server">
    <link href="~/Styles.css" rel="stylesheet" type="text/css" />
</head>