A Useful Tag: base href

Posted on 2007.11.26
Categories: XHTML; Tagged with: , , , , ,

If you’re coding in XHTML or if you’re creating a site in PHP, one of the pains is making sure that your relative paths are correct. Surely having to type in the full site URL is a pain, even though that would usually eliminate the relative paths problem; but instead of using
<link href="../../style/style.css" rel="stylesheet" media="screen" />
and trying to make sure that the above code works for every page of your design, you could simply utilize the easy and simple,
<base href="http://www.example.com/" />
tag!

First of all, in using the base href tag, there is no need to re-type the entire absolute URL every time you are looking for an image, such as
<img src="http://www.geekie.org/wp-content/themes/default/demo.gif" alt="demo image, not a real image" />

If you declare that every single relative path in your XHTML document in the form “something/something.ext” (without the preceding slash!), is relative to a “base href”, every relative URL will be loaded correctly, with no need to type in a long absolute URL.

If you’re using PHP, and you have to account for shared SSL, it’s even more useful! Simply declare a variable for the value of this “base href” when the following condition is true:

<?php
if($_SERVER['SERVER_PORT']==’443′) {
$base_href_value = ‘https://www.freddyware.org/~username/’;
}
?>

Of course, the code above can be written in the ternary operator form, but that’s a lesson for the PHP section, another day.

If you let your base href tag change according to PHP’s evaluation of certain conditions, you can effectively maintain correct relative URL’s regardless of what domain your site is being accessed at, and utilizing the method above, you can also prevent SSL errors. Should your site reside in a folder other than the site root, this is especially useful for preventing errors.

Please make sure that you test your code before deploying it.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

no comments yet.

Leave a comment

Names and email addresses are required (email addresses aren't displayed), url's are optional.

Comments may contain the following xhtml tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comments by unregistered users need approval, and all comments are subject to Akismet SPAM filtering. A valid e-mail address is required but will not be published or used for third-party solicitation (see our Privacy Policy). Please provide either your real name or a nickname representative of yourself.