Absolute vs Relative URLs

May 16, 2006     

After 10 years you’d think I’d have come to a firm conclusion on whether to use absolute or relative URLs in my HTML. It’s a simple choice:

<img src="/images/image.jpg" />


<img src="images/image.jpg" />

I’ve tended to favor absolute URLs for images and javascripts over the years. For links to pages, it usually makes sense to use relative URLs within sections of a site (ie. within a subdirectory that may be moved as a cohesive unit) But it’s far from a no brainer.

Pros of Absolute URLs

  • Work no matter where source HTML files.
  • Work well with clean URL schemes (this is huge).
  • They can make it easier to move some HTML from a preview directory to a live directory in some cases.

Cons of Absolute URLs

  • Locations of absolute URLs can not be changed lightly (but should they change?).
  • Can break down when a site is moved from user directory hosted website to it’s own URL (ie. http://genericdomain.com/~my_user/ to http://mydomain.com).
  • They can make it harder to move some HTML from a preview directory to a live directory in some cases.

Web applications and frameworks tend to solve this problem nicely. Rails, for instance is pretty intelligent about generating good URLs. And really any decent framework will centralize link generation so that you can easily modify all the links on a site as necessary.

The real problem is those static links to images, stylesheets and scripts that number in the thousands and have the capability to render a site useless with no quick fix. If you’re a wizard then you can maybe do some global regexp search and replaces, but that’s risky. I’ve also had some success using mod_rewrite for a temporary fix. But from a maintainability perspective there’s still no right way to set up your URLs. You can get burned no matter what you choose.

Have a nice day!