Bespoke Windows and Web Development

5Aug 08

The Importance of the Slash

Adding a slash to the end of a link to a directory turns out to be important - who knew, oh, you knew, well I didn't ...

Part of the new Gallery 3.0 development is to have a preview of the generated gallery. You may think you could just launch the browser at the given file on you hard disk and away you go. But no, to see the gallery working correctly it needs to be hosted by an HTTP server, default documents being the main reason (e.g. browse to C:\Gallery and you'll get a directory listing). This means that I'll have to embed a HTTP server in the app, and not wanting to use one of the many existing open source C# HTTP Servers like Cassini or aspNetServe etc. because the do much more than I need, and I couldn't get them working on plain ol' html files, I decided to have a go at one myself.

As with all well established protocols HTTP benefits from plenty of documentation, from the official RFC 2616 to unofficial but very helpful articles such as James Marshall's HTTP Made Really Easy. So its not to difficult to get a good start. I did, however, get a bit stuck on one small point which I found difficult to find info on, mainly because I wasn't sure what was wrong, hence this entry.

Basically, I built the server to respond to GET calls from the browser, which would convert the requested URL into a local path and return the file found in the response...

Request

GET / HTTP/1.1
This would return the default document, i.e. default.htm.

The difficulty came when I requested the following:

Request

GET /Picture1 HTTP/1.1
Note the lack of ending slash '/' even though it is a directory

Although, I made sure that this returned the default document as expected, subsequent calls from the browser for images and stylesheets did not have the correct relative path.

Turns out that without a slash the browser doesn't know its in a directory and won't add the directory name to the subsequent calls so you get

Request

GET /Image.jpg HTTP/1.1
instead of
GET /Picture1/Image.jpg HTTP/1.1

So, what's the solution?
Well, using Firefox's excellent add-on Firebug and the VS Development server I could see a 302 Found response being sent, to let the browser know that it was hitting a directory and not a file. This prompts the browser to make a new request using the location header sent in the 302 response, in this case, the same URL, but adding a trailing slash.

Doing the same in my code fixed it proper. Hoorah!

Request

GET /Picture1 HTTP/1.1

Response

HTTP/1.1 302 Found
Location: /Picture1/

This also suggest that you can get a quicker response if you add a trailing slash to you directory links.

Well, there you are then.

ps. I've created a small stand-alone application you can try

HTTP, Browsers, Development