<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.2.3" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>Sebastian's Pamphlets &#187; Redirects</title>
	<link>http://sebastians-pamphlets.com</link>
	<description>If you've read my articles somewhere on the Internet, expect something different here.</description>
	<pubDate>Wed, 03 Mar 2010 19:45:08 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.2.3</generator>
	<language>en</language>
			<item>
		<title>How brain-amputated developers created the social media plague</title>
		<link>http://sebastians-pamphlets.com/social-media-plague/</link>
		<comments>http://sebastians-pamphlets.com/social-media-plague/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 17:36:50 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Social Web]]></category>

		<category><![CDATA[X-Robots-Tag]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[URI shortening]]></category>

		<category><![CDATA[Trolling]]></category>

		<category><![CDATA[Web development]]></category>

		<category><![CDATA[Crap]]></category>

		<category><![CDATA[Crawler Directives]]></category>

		<category><![CDATA[Robots Meta Tags]]></category>

		<category><![CDATA[Twitter]]></category>

		<category><![CDATA[robots.txt]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/social-media-plague/</guid>
		<description><![CDATA[
The bot playground commonly refered to as &#8220;social media&#8221; is responsible for shitloads of absurd cretinism.
For example Twitter, where gazillions of bots [type A] follow other equally superfluous but nevertheless very busy bots [type B] that automatically generate 27% valuable content (links to penis enlargement tools) and 73% not exactly exciting girly chatter (breeding demand [...]]]></description>
			<content:encoded><![CDATA[
<p>The bot playground commonly refered to as &#8220;social media&#8221; is responsible for shitloads of absurd cretinism.</p>
<p><img src="http://sebastians-pamphlets.com/img/posts/sm-plague-bot-playground.png" width="195" height="246" align="right" style="margin-left:5px;" alt="Twitter Bot Playground" title=""  />For example <a href="https://twitter.com/SebastianX">Twitter</a>, where gazillions of bots [type A] follow other equally superfluous but nevertheless very busy bots [type B] that automatically generate <a href="http://holykaw.alltop.com/only-27-of-tweets-contain-value-says-new-stud">27%</a> valuable content (links to penis enlargement tools) and 73% not exactly exciting girly chatter (breeding demand for cheap viagra).</p>
<p>Bazillions of other bots [type C] retweet bot [type B] generated crap and create lists of bots [type A, B, C]. In rare cases when a non-bot tries to participate in Twitter, the uber-bot [type T] prevents the whole bot network from negative impacts by serving a 503 error to the homunculus&#8217; browser.</p>
<p>This pamphlet is about the idiocy of a particular subclass of bots [type S] that sneakily work in the underground stealing money from content producers, and about their criminal (though brain-dead) creators. May they catch the swine flu, or at least pox or cholera, for the pest they&#8217;ve brought to us.</p>
<h3 id="sm-plague-the-pest">The Twitter pest that costs you hard earned money</h3>
<p>WTF I&#8217;m ranting about? The technically savvy reader, familiar with my attitude, has already figured out that I&#8217;ve read way too many raw logs. For the sake of a common denominator, I encourage you to perform a tiny real-world experiment:</p>
<ul>
<li>Publish a great and linkworthy piece of content.</li>
<li>Tweet its URI (not shortened - message incl. URI &le; 139 characters!) with a compelling call for action.</li>
<li>Watch your server logs.</li>
<li>Puke. Vomit increases with every retweet.</li>
</ul>
<p>So what happens on your server? A greedy horde of bots pounces on every tweet containing a link, requesting its content. That&#8217;s because on Twitter all URIs are suspected to be shortened (<a href="http://tag.us.com/uri-shorteners-suck-ass.htm#twitter-crap">learn <i>why</i> Twitter makes you eat shit</a>). This uncalled-for &#8211;IOW abusive&#8211; bot traffic burns your resources, and (with a cheap hosting plan) it can hinder your followers to read your awesome article and prevent them from clicking on your carefully selected ads.</p>
<p>Those crappy bots not only cost you money because they keep your server busy and increase your bandwidth bill, they actively decrease your advertising revenue because your visitors hit the back button when your page isn&#8217;t responsive due to the heavy bot traffic. Even if you&#8217;ve great hosting, you probably don&#8217;t want to burn money, not even pennies, right? </p>
<h3 id="sm-plague-mo">Bogus Twitter apps and their modus operandi</h3>
<p>If only every Twitter&amp;Crap-mashup would lookup each URI once, that wouldn&#8217;t be such a mess. Actually, some of these crappy bots request your stuff 10+ times per tweet, and again for each and every retweet. That means, as more popular your content becomes, as more bot traffic it attracts.</p>
<p>Most of these bots don&#8217;t obey <a href="http://sebastians-pamphlets.com/links/categories/?cat=robotstxt">robots.txt</a>, that means you can&#8217;t even block them applying Web standards (<a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-rogue-bot">learn how to block rogue bots</a>). <a href="http://labs.topsy.com/butterfly/">Topsy</a>, for example, does respect the content producer &#8212; so morons using &#8220;Python-urllib/1.17&#8243; or &#8220;AppEngine-Google; (+http://code.google.com/appengine; appid: mapthislink)&#8221; could obey the <a href="http://www.robotstxt.org/">Robots Exclusion Protocol</a> (REP), too. Their developers are just too fucking lazy to understand such protocols that every respected service on the Web (search engines&#8230;) obeys.</p>
<p>Some of these bots even provide an HTTP_REFERER to lure you into viewing the website operated by their shithead of developer when you&#8217;re viewing your referrer stats. Others fake Web browsers in their user agent string, just in case you&#8217;re not smart enough to smell shit that really stinks (IOW browser-like requests that don&#8217;t fetch images, CSS files, and so on).</p>
<p>One of the worst offenders is outing itself as &#8220;ThingFetcher&#8221; in the user agent string. It&#8217;s hosted by Rackspace, which is a hosting service that obviously doesn&#8217;t care much about its reputation. Otherwise these guys would have reacted to my <a href="http://friendfeed.com/sebastianx/81c0792e/rackspace-you-host-abusive-bot-thingfetcher">various</a> <a href="http://friendfeed.com/sebastianx/80a3165c/owner-of-thingfetcher-should-stand-up-now-i-m" title="A Rackspace employee did read this tweet">complaints</a> WRT &#8220;ThingFetcher&#8221;. By the way, <a href="http://scobleizer.com/">Robert Scoble</a> represents Rackspace, you could <a href="http://twitter.com/scobelizer">drop him a line</a> if ThingFetcher annoys you, too.</p>
<p>ThingFetcher sometimes requests a (shortened) URI 30 times per second, from different IPs. It can get worse when a URI gets retweeted often. This malicious piece of code doesn&#8217;t obey robots.txt, and doesn&#8217;t cache results. Also, it&#8217;s too dumb to follow chained redirects, by the way. It doesn&#8217;t even publish its results anywhere, at least I couldn&#8217;t find the fancy URIs I&#8217;ve feeded it with in Google&#8217;s search index.</p>
<p>In ThingFetcher&#8217;s defense, its developer might say that it performs only <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4" title="The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.">HEAD requests</a>. Well, it&#8217;s true that HEAD request provoke only an HTTP response header. But: the script invoked gets completely processed, just the output is trashed.</p>
<p>That means, the Web server has to deal with the same load as with a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3" title="The GET method means retrieve whatever information (...) is identified by the Request-URI.">GET request</a>, it just deletes the content portion (the compelety formatted HTML page) when responding, after counting its size to send the <code>Content-Length</code> response header. Do you really believe that I don&#8217;t care about machine time? For each of your <del>utterly useless</del> <ins>bogus</ins> requests I could have my server deliver ads to a human visitor, who pulls the plastic if I&#8217;m upselling the right way (I do, usually).</p>
<p>Unfortunately, ThingFetcher is not the only bot that does a lookup for each URI embedded in a tweet, per tweet processed. Probably the overall number of URIs that appear only once is bigger than the number of URIs that appear quite often while a retweet campaign lasts. That means that doing HTTP requests is cheaper for the bot&#8217;s owner, but on the other hand that&#8217;s way more expensive for the content producer, and the URI shortening services involved as well.</p>
<p style="margin-left:15px;" id="sm-plague-upd-thingfetcher"><strong>ThingFetcher update:</strong> The owners of ThingFetcher are now aware of the problem, and will try to fix it asap (<a href="http://friendfeed.com/sebastianx/5e00fc9e/shellen-cw-let-move-this-discussion-to">more information</a>). Now that I know who&#8217;s operating the Twitter app owning ThingFetcher, <del>I take back the insults above</del> <ins>I&#8217;ve removed some insults from above, because they&#8217;d no longer address an anonymous developer, but bright folks who&#8217;ve just failed once</ins>. Too sad that <a href="http://brizzly.com/">Brizzly</a> didn&#8217;t reply earlier to my <a href="http://friendfeed.com/search?q=ThingFetcher">attempts</a> to identify ThingFetcher&#8217;s owner.</p>
<p>As a content producer I don&#8217;t care about the costs of any Twitter application that processes Tweets to deliver anything to its users. I care about my costs, and I can perfecly live without such a crappy service. Liberally, I can allow one single access per (shortened) URI to figure out its final destination, but I can&#8217;t tolerate such thoughtless abuse of my resources.</p>
<p>Every Twitter related &#8220;service&#8221; that does multiple requests per (shortened) URI embedded in a tweet is guilty of theft and pilferage. Actually, that&#8217;s an understatement, because these raids cost publishers an enormous sum across the Web. </p>
<p>These fancy apps shall maintain a database table storing the destination of each redirect (chain) acessible by its short URI. Or leave the Web, respectively pay the publishers. And by the way, Twitter should finally end URI shortening. Not only it breaks the Internet, it&#8217;s way too expensive for all of us.</p>
<h3 id="sm-plague-offenders">A few more bots that need a revamp, or at least minor tweaks</h3>
<p>I&#8217;ve added this section to express that besides my prominent <a href="http://sebastians-pamphlets.com/social-media-plague/#sm-plague-upd-thingfetcher">example</a> above, there&#8217;s more than one Twitter related app running not exactly squeaky clean bots. That&#8217;s not a &#8220;worst offenders&#8221; list, it&#8217;s not complete (I don&#8217;t want to reprint <a href="http://twitter.com/downloads">Twitter&#8217;s yellow pages</a>), and bots are listed in no particular order (compiled from requests following the link in a <a href="http://twitter.com/SebastianX/status/7784746783">test tweet</a>, evaluating only a snapshot of less than 5 minutes, backed by historized logs.)</p>
<p><small><a href="http://sebastians-pamphlets.com/social-media-plague/#sm-plague-howto">Skip examples</a></small></p>
<p id="sm-plague-tweetmeme"><a href="http://tweetmeme.com/about" rel="nofollow">Tweetmeme</a>&#8217;s <b>TweetmemeBot</b> coming from eagle.favsys.net doesn&#8217;t fetch robots.txt. On their site they don&#8217;t explain why they don&#8217;t respect the robots exclusion protocol (REP). Apart from that it behaves.</p>
<p  id="sm-plague-oneriot"><a href="http://www.oneriot.com/company/about" rel=nofollow>OneRiot&#8217;s</a> bot <b>OneRiot/1.0</b> totally proves that this real time search engine has chosen a great name for itself. Performing 5+ GET as well as HEAD requests per link in a tweet (sometimes more) certainly counts as rioting. Requests for content come from different IPs, the host name pattern is <code>flx1-ppp*.lvdi.net</code>, e.g. flx1-ppp47.lvdi.net. From the same IPs comes another bot:  <b>Me.dium/1.0</b>, me.dium.com redirects to oneriot.com.  OneRiot doesn&#8217;t respect the REP.</p>
<p id="sm-plague-bing"><b>Microsoft/Bing</b> runs abusive bots following links in tweets, too. They fake browsers in the user agent, make use of IPs that don&#8217;t obviously point to Microsoft (no host name, e.g. 65.52.19.122, 70.37.70.228 &#8230;), send multiple GET requests per processed tweet, and don&#8217;t respect the REP. If you need more information, I&#8217;ve ranted about <a href="http://sebastians-pamphlets.com/links/categories/?cat=msn">deceptive M$-bots</a> before. Just a remark in case you&#8217;re going to block abusive MSN bot traffic:</p>
<p>MSN/Bing reps ask you not to block their spam bots when you&#8217;d like to stay included in their search index (that goes for real time search, too), but who really wants that? Their search index is tiny &#8211;compared to other search engines like Yahoo and Google&#8211;, their discovery crawling <a href="http://blogs.perl.org/users/cpan_testers/2010/01/msnbot-must-die.html">sucks</a> &#8211;to get indexed you need to submit your URIs at their <a href="http://tag.us.com/_submit2bing">webmaster forum</a>&#8211;, and in most niches you can count your yearly Bing SERP referrers using not even all fingers of your right hand. If your stats show more than that, check your raw logs. You&#8217;ll soon figure out that MSN/Bing spam bots fake SERP traffic in the HTTP_REFERER (guess where their &#8220;impressive&#8221; market share comes from).</p>
<p id="sm-plague-friendfeed"><a href="http://friendfeed.com/">FriendFeed</a>&#8217;s bot <b>FriendFeedBot/0.1</b> is well explained, and behaves. Its <a href="http://friendfeed.com/about/bot">bot page</a> even lists all its IPs, and provides you with an email addy for complaints (I never had a reason to use it). The FriendFeedBot made it on this list just because of its lack of REP support.</p>
<p id="sm-plague-postrank"><a href="http://postrank.com/" rel="nofollow">PostRank</a>&#8217;s bot <b>PostRank/2.0</b> comes from Amazon IPs. It doesn&#8217;t respect the REP, and does more than one request per URI found in one single tweet.</p>
<p id="sm-plague-markmonitor"><a href="http://markmonitor.com/" rel="nofollow">MarkMonitor</a> operates a bot faking browser requests, coming from *.embarqhsd.net (va-71-53-201-211.dhcp.embarqhsd.net, va-67-233-115-66.dhcp.embarqhsd.net, &#8230;). Multiple requests per URI, no REP support.</p>
<p id="sm-plague-cuil"><a href="http://www.cuil.com/" rel="nofollow">Cuil</a>&#8217;s bot provides an empty user agent name when following links in tweets, but fetches robots.txt like Cuil&#8217;s offical crawler <b>Twiceler</b>. I didn&#8217;t bother to test whether this Twitter bot can be blocked following <a href="http://www.cuil.com/info/webmaster_info/">Cuil&#8217;s instructions for webmasters</a> or not. It got included in this list for the supressed user agent.</p>
<p id="sm-plague-twingly"><a href="http://www.twingly.com/" rel="nofollow">Twingly</a>&#8217;s bot  <b>Twingly Recon</b> coming from *.serverhotell.net doesn&#8217;t respect the REP, doesn&#8217;t name its owner, but does only few HEAD requests. </p>
<p id="sm-plague-anon-bots">Many bots mimicking browsers come from Amazon, Rackspace, and other cloudy environments, so you can&#8217;t get hold of their owners without submitting a report-abuse form. You can identify such bots by sorting your access logs by IP addy. Those &#8220;browsers&#8221; which don&#8217;t request your images, CSS files, and so on, are most certainly bots. Of course, a human visitor having cached your images and CSS matches this pattern, too. So block only IPs that solely request your HTML output over a longer period of time (problematic with bots using DSL providers, AOL, &#8230;).</p>
<p>Blocking requests (with IPs belonging to consumer ISPs, or from Amazon and other dynamic hosting environments) with a user agent name like &#8220;LWP::Simple/5.808&#8243;, &#8220;PycURL/7.18.2&#8243;, &#8220;my6sense/1.0&#8243;, &#8220;Firefox&#8221; (just these 7 characters), &#8220;Java/1.6.0_16&#8243; or &#8220;libwww-perl/5.816&#8243; is sound advice. By the way, these requests sum up to an amount that would lead a &#8220;worst offenders&#8221; listing. </p>
<p id="sm-plague-edu">Then there are students doing research. I&#8217;m not sure I want to waste my resources on requests from Moscow&#8217;s &#8220;Institute for System Programming RAS&#8221;, which fakes unnecessary loads of human traffic (from efrate.ispras.ru, narva.ispras.ru, dvina.ispras.ru &#8230;), for example.</p>
<p id="sm-plague-nasty-bots">When you analyze bot traffic following a tweet with many retweets, you&#8217;ll gather a way longer list of misbehaving bots. That&#8217;s because you&#8217;ll catch more 3rd party Twitter UIs when many Twitter users view their timeline. Not all Twitter apps route their short URI evaluation through their servers, so you might miss out on abusive requests coming from real users via client sided scripts.</p>
<p id="sm-plague-bot-devs">Developers might argue that such requests &#8220;on behalf of the user&#8221; are neither abusive, nor count as bot traffic. I assure you, that&#8217;s crap, regardless a particular Twitter app&#8217;s architecture, when you count more than one evaluation request per (shortened) URI. For example Googlebot acts on behalf of search engine users too, but it doesn&#8217;t overload your server. It fetches each URI embedded in tweets only once. And yes, it processes all tweets out there.</p>
<h3 id="sm-plague-howto">How to do it the right way</h3>
<p>Here is what a site owner can expect from a Twitter app&#8217;s Web robot:</p>
<h4 id="sm-plague-howto-ua">A meaningful user agent</h4>
<p>A Web robot must provide a user agent name that fulfills at least these requirements:</p>
<ul>
<li>A unique string that identifies the bot. The unique part of this string must not change when the version changes (&#8221;somebot/1.0&#8243;, &#8220;somebot/2.0&#8243;, &#8230;).</li>
<li>A URI pointing to a page that explains what the bot is all about, names the owner, and tells how it can be blocked in robots.txt (like <a href="http://labs.topsy.com/butterfly/">this</a> or <a href="http://www.alexa.com/help/webmasters">that</a>).</li>
<li>A hint on the rendering engine used, for example &#8220;Mozilla/5.0 (compatible; &#8230;&#8221;.</li>
</ul>
<h4 id="sm-plague-howto-revip">A method to verify the bot</h4>
<p>All IP addresses used by a bot should resolve to server names having a unique pattern. For example Googlebot comes only from servers named <code>"crawl" + "-" + replace($IP, ".", "-") + ".googlebot.com"</code>, e.g. &#8220;crawl-66-249-71-135.googlebot.com&#8221;. All major search engines follow this standard that enables crawler detection not solely relying on the easily spoofable user agent name. </p>
<h4 id="sm-plague-howto-robots-txt">Obeying the robots.txt standard</h4>
<p>Webmasters must be able to steer a bot with crawler directives in <a href="http://sebastians-pamphlets.com/links/categories/?cat=robotstxt">robots.txt</a> like &#8220;Disallow:&#8221;. A Web robot should fetch a site&#8217;s /robots.txt file before it launches a request for content, when it doesn&#8217;t have a cached version from the same day.</p>
<h4 id="sm-plague-howto-indexer-directives">Obeying REP indexer directives</h4>
<p>Indexer directives like &#8220;nofollow&#8221;, &#8220;noindex&#8221; et cetera must be obeyed. That goes for HEAD requests just chasing for a 301/302/307 redirect response code and a &#8220;location&#8221; header, too.</p>
<p>Indexer directives can be served in the HTTP response header with an <a href="http://sebastians-pamphlets.com/links/categories/?cat=x-robots-tag">X-Robots-Tag</a>, and/or in META elements like the <a href="http://sebastians-pamphlets.com/links/categories/?cat=robots-meta-tags">robots meta tag</a>, as well as in LINK elements like <a href="http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html?utm_source=sebastian&#038;utm_medium=pamphlet&#038;utm_campaign=thou+shalt+not+fuck+with+my+uris">rel=canonical</a> and its <a href="http://sebastians-pamphlets.com/x-canonical-uri-http-header/">corresponding headers</a>.</p>
<h4 id="sm-plague-howto-behave">Responsible behavior</h4>
<p>As outlined above, requesting the same resources over and over doesn&#8217;t count as responsible behavior. Fetching or &#8220;HEAD&#8217;ing&#8221; a resource no more than once a day should suffice for every Twitter app&#8217;s needs.</p>
<h4 id="sm-plague-howto-copyright">Respecting copyrights</h4>
<p>Reprinting a page&#8217;s content, or just large quotes, doesn&#8217;t count as fair use. It&#8217;s Ok to grab the page title and a summary from a META element like &#8220;description&#8221; (or up to 250 characters from an article&#8217;s first paragraph) to craft links, for example - but not more! Also, showing images or embedding videos from the crawled page violates copyrights.</p>
<h3 id="sm-plague-conclusion">Conclusion, and call for action</h3>
<p>If you suffer from rogue Twitter bot traffic, use the medium those bots live in to make their sins public knowledge. Identify the bogus bot&#8217;s owners and tweet the crap out of them. Lookup their hosting services, find the report-abuse form, and submit your complaints. Most of these apps make use of the Twitter-API, there are <a href="http://twitter.zendesk.com/forums/26257/entries/15789">many spam report forms</a> you can creatively use to ruin their reputation at Twitter. If you&#8217;ve an account at such a bogus Twitter app, then cancel it and encourage your friends to follow suit.</p>
<p><strong>Don&#8217;t let the assclowns of the Twitter universe get away with theft!</strong></p>
<p>I&#8217;d like to hear about particular offenders you&#8217;re dealing with, and your defense tactics as well, in the comments. Don&#8217;t be shy. Go rant away. Thanks in advance!</p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/social-media-plague/", "style": "big", "title": "How brain-amputated developers created the social media plague" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/social-media-plague/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How to cleverly integrate your own URI shortener</title>
		<link>http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/</link>
		<comments>http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 14:20:25 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[URI shortening]]></category>

		<category><![CDATA[Usability]]></category>

		<category><![CDATA[404grabber]]></category>

		<category><![CDATA[Web development]]></category>

		<category><![CDATA[Social Web]]></category>

		<category><![CDATA[Site-Search]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/</guid>
		<description><![CDATA[
This pamphlet is somewhat geeky. Don&#8217;t necessarily understand it as a part of my ongoing jihad holy war on URI shorteners.
Assuming you&#8217;re slightly familiar with my opinions, you already know that third party URI shorteners (aka URL shorteners) are downright evil. You don&#8217;t want to make use of unholy crap, so you need to roll [...]]]></description>
			<content:encoded><![CDATA[
<p>This pamphlet is somewhat geeky. Don&#8217;t necessarily understand it as a part of my ongoing <a href="http://sebastians-pamphlets.com/put-an-end-to-uri-shortening/"><strike>jihad</strike></a> holy war on URI shorteners.</p>
<p><img src="http://sebastians-pamphlets.com/img/posts/clever-404-handler-with-sURI.png"  width="279" height="1008" align="left" style="margin-right:5px;" alt="Clever implementation of an URL shortener" title="How to implement an URL shortener cleverly" />Assuming you&#8217;re slightly familiar with my opinions, you already know that third party URI shorteners (aka URL shorteners) are <a href="http://sebastians-pamphlets.com/links/categories/?cat=s-url">downright evil</a>. You don&#8217;t want to make use of unholy crap, so you need to roll your own. Here&#8217;s how you can (could) integrate a URI shortener into your site&#8217;s architecture.</p>
<p>Please note that my design suggestions ain&#8217;t black nor white. Your site&#8217;s architecture may require a different approach. Adapt my tips with care, or use my thoughts to rethink your architectural decisions, if they&#8217;re applicable.</p>
<p>At the first sight, <a href="http://www.google.com/search?hl=en&#038;safe=off&#038;num=100&#038;q=free+URL+shortener+script">searching for a free URI shortener script</a> to implement it on a dedicated domain looks like a pretty simple solution. It&#8217;s not. At least not in most cases. Standalone URI shorteners work fine when you want to shorten mostly foreign URIs, but that&#8217;s a crappy approach when you want to submit your own stuff to social media. Why? Because you throw away the ability to totally control your traffic from social media, and search engine traffic generated by social media as well.</p>
<p>So if you&#8217;re not running <code>cheap-student-loans-with-debt-consolidation-on-each-payday-is-a-must-have-for-sexual-heroes-desperate-for-a-viagra-overdose-and-extreme-penis-length-enhancement.info</code> and your domain&#8217;s name without the &#8220;www&#8221; prefix plus a few characters gives URIs of 20 (30) characters or less, you don&#8217;t need a short domain name to host your shortened URIs.</p>
<p id="twitter-suri-obsolete">As a side note, when you&#8217;re shortening your URIs for <a href="http://tag.us.com/uri-shorteners-suck-ass.htm#twitter-crap">Twitter</a> you should know that <strong>shortened URIs aren&#8217;t mandatory</strong> any more. If your message doesn&#8217;t exceed 139 characters, you don&#8217;t need to shorten embedded URIs.</p>
<p>By integrating a URI shortener into your site architecture you gain the abilitiy to perform way more than URI shortening. For example, you can transform your longish and ugly dynamic URIs into short (but keyword rich) URIs, and more.</p>
<p>In the following I&#8217;ll walk you step by step through (not really) everything an incoming HTTP request might face. Of course the sequence of steps is a generalization, so perhaps you&#8217;ll have to change it to fit your needs. For example when you operate a WordPress blog, you could code nearly everthing below in your 404 page (consider <a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-dynamic-stuff">alternatives</a>). Actually, handling short URIs in your error handler is a pretty good idea when you suffer from a mainstream CMS.</p>
<h3 id="sUri-impl-toc">Table of contents</h3>
<p>To provide enough context to get the advantages of a fully integrated URI shortener, vs. the stand-alone variant, I&#8217;ll bore you with a ton of dull and totally unrelated stuff:</p>
<ul>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-rogue-bot">Block rogue bots</a></li>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-srv-name">Server name canonicalization</a></li>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-static-stuff">Deliver static stuff (images &#8230;)</a></li>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-dynamic-stuff">Execute script (dynamic URI)</a></li>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-short-uri">Resolve shortened URI</a> (<a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-components">Anatomy of a URI shortener</a>)</li>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-redirect">Redirect to destination (invalid request)</a></li>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-guess-uri">Guess destination (invalid request)</a></li>
<li><a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-error-page">Serve a useful error page</a></li>
</ul>
<h3 id="sUri-code-intro">Introduction</h3>
<p>There&#8217;s a bazillion of methods to handle HTTP requests. For the sake of this pamphlet I assume we&#8217;re dealing with a well structured site, hosted on Apache with mod_rewrite and PHP available. That allows us to handle each and every HTTP request dynamically with a PHP script. To accomplish that, upload an .htaccess file to the document root directory:</p>
<p><code>RewriteEngine On</code><br />
<code>RewriteCond  %{SERVER_PORT} ^80$</code><br />
<code>RewriteRule . /requestHandler.php [L]</code></p>
<p>Please note that the code above kinda disables the Web server&#8217;s error handling. If <code><br />/requestHandler.php</code> exists in the root directory, all <a href="http://sebastians-pamphlets.com/why-proper-error-handling-is-important/">ErrorDocument directives</a> (except some 5xx) et cetera will be ignored. You need to <a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-error-page">take care of errors</a> yourself.</p>
<p><b>/requestHandler.php</b> (Warning: untested and simplified code snippets below)<br /><code> /* Initialization */<br />
$serverName          = strtolower($_SERVER["SERVER_NAME"]);<br />
$canonicalServerName = "sebastians-pamphlets.com";<br />
$scheme              = "http://";<br />
$rootUri             = $scheme .$canonicalServerName; /* if used w/o path add a </code><a href="http://sebastians-pamphlets.com/thou-must-not-steal-the-trailing-slash-from-my-urls/">slash</a><code> */<br />
$rootPath            = $_SERVER["DOCUMENT_ROOT"];<br />
$includePath         = $rootPath ."/src"; /* Customize that, maybe you've to manipulate the file system path to your Web server's root */<br />
$requestIp           = $_SERVER["REMOTE_ADDR"];<br />
$reverseIp           = NULL;<br />
$requestReferrer     = $_SERVER["HTTP_REFERER"];<br />
$requestUserAgent    = $_SERVER["HTTP_USER_AGENT"];<br />
$isRogueBot          = FALSE;<br />
$isCrawler           = NULL;<br />
$requestUri          = $_SERVER["REQUEST_URI"];<br />
$absoluteUri         = $scheme .$canonicalServerName .$requestUri;<br />
$uriParts            = parse_url($absoluteUri);<br />
$requestScript       = $PHP_SELF;<br />
$httpResponseCode    = NULL;<br />
</code></p>
<h3 id="sUri-impl-rogue-bot">Block rogue bots</h3>
<p>You don&#8217;t want to waste resources by serving your valuable content to useless bots. Here are a few ideas how to block rogue (crappy, not behaving, &#8230;) Web robots. If you need a top-notch nasty-bot-handler please contact the authority in this field: <a href="http://twitter.com/IncrediBill">IncrediBill</a>.</p>
<p>While handling bots, you should detect search engine crawlers, too:</p>
<p><code>/* lookup your </code><a href="http://fantomaster.com/fasvsspy01.html">crawler IP database</a><code> to populate $isCrawler; then, if the IP wasn't identified as search engine crawler: */<br />
if ($isCrawler !== TRUE) {<br />
    $crawlerName         = NULL;<br />
    $crawlerHost         = NULL;<br />
    $crawlerServer       = NULL;<br />
    if (stristr($requestUserAgent,"Baiduspider")) {$crawlerName = "Baiduspider"; $crawlerServer = ".crawl.baidu.com";}<br />
    ...<br />
    if (stristr($requestUserAgent,"Googlebot")) {$crawlerName = "Googlebot"; $crawlerServer = ".googlebot.com"; }<br />
    if ($crawlerName != NULL) {<br />
        $reverseIp = @gethostbyaddr($requestIp);<br />
        if (!stristr($reverseIp,$crawlerServer)) {<br />
            $isCrawler = FALSE;<br />
        }<br />
        if ("$reverseIp" == "$requestIp") {<br />
            $isCrawler = FALSE;<br />
        }<br />
        if ($isCrawler !== FALSE;) {<br />
            $chkIpAddyRev = @gethostbyname($reverseIp);<br />
            if ("$chkIpAddyRev" == "$requestIp") {<br />
                $isCrawler   = TRUE;<br />
                $crawlerHost = $reverseIp;<br />
                // store the newly discovered crawler IP<br />
            }<br />
        }<br />
    }<br />
}<br />
</code></p>
<p>If Baidu doesn&#8217;t send you any traffic, it makes sense to block its crawler. This piece of crap doesn&#8217;t behave anyway.<code><br />if ($isCrawler &amp;&amp;</code><code> "$crawlerName" == "Baiduspider") {<br />
$isRogueBot = TRUE;<br />
}<br />
</code></p>
<p>Another SE candidate is <a href="http://sebastians-pamphlets.com/msn-admits-clueless-and-ineffective-spamming/">Bing&#8217;s spam bot</a> that tries to manipulate stats on search engine usage. If you don&#8217;t approve such scams, block incoming<span style="color:silver;">!</span> from the IP address range 65.52.0.0 to 65.55.255.255 (131.107.0.0 to 131.107.255.255 &#8230;) when the referrer is a Bing SERP. With this method you occasionally might block searching Microsoft employees who aren&#8217;t aware of their company&#8217;s spammy activities, so make sure you serve them a friendly GFY page that explains the issue. </p>
<p>Other rogue bots identify themselves by IP addy, user agent, and/or referrer. For example some bots spam your referrer stats, just in case when viewing stats you&#8217;re in the mood to consume porn, consolidate your debt, or buy cheap viagra. Compile a list of NSAW keywords and run it against the HTTP_REFERER:<code><br />if (notSafeAtWork($requestReferrer)) {$isRogueBot = TRUE;}</code><br />If you operate a porn site you should refine this approach.</p>
<p>As for blocking requests by IP addy I&#8217;d recommend a spamIp database table to collect IP addresses belonging to rogue bots. Doing a <code>@gethostbyaddr($requestIp)</code> DNS lookup while processing HTTP requests is way too expensive (with regard to performance). Just read your raw logs and add IP addies of bogus requests to your black list.<code><br />if (isBlacklistedIp($requestIp)) {$isRogueBot = TRUE;}</code></p>
<p>You won&#8217;t believe how many rogue bots still out themselves by supplying you with a unique user agent string. Go search for [<a href="http://www.google.com/search?hl=en&#038;safe=off&#038;num=100&#038;q=block+user+agent">block user agent</a>], then pick what fits your needs best from rougly two million search results. You should maintain a database table for ugly user agents, too. Or code<code><br />if (<span style="color:silver;">isBlacklistedUa($requestUserAgent) ||</span></code><code><br /> stristr($requestUserAgent,&#8221;ThingFetcher&#8221;)) {$isRogueBot = TRUE;}</code><br />By the way, the owner of ThingFetcher really should stand up now. I&#8217;ve sent a complaint to Rackspace and I&#8217;ve blocked your misbehaving bot on various sites because it performs excessive loops requesting the same stuff over and over again, and doesn&#8217;t bother to check for robots.txt.</p>
<p>Finally, serve rogue bots what they deserve:<code><br />if ($isRogueBot === TRUE) {</code><code><br />
header("HTTP/1.1 403 Go fuck yourself", TRUE, 403);<br />
exit;<br />
}</code></p>
<p>If you&#8217;re picky, you could make some fun out of these requests. For example, when the bot provides an HTTP_REFERER (the page you should click from your referrer stats), then just do a <code>file_get_contents($requestReferrer);</code> and serve the slutty bot its very own crap. Or just 301 redirect it to the referrer provided, to http://example.com/go-fuck-yourself, or something funny like a huge image gfy.jpeg.html on a freehost (not that such bots usually follow redirects). I&#8217;d go for the 403-GFY response.</p>
<h3 id="sUri-impl-srv-name">Server name canonicalization</h3>
<p>Although search engines have learned to deal with multiple URIs pointing to the same piece of content, sometimes their URI canonicalization routines do need your support. At least make sure you serve your content under <b>one</b> server name:<code><br />if (&#8221;$serverName&#8221; != &#8220;$canonicalServerName&#8221;) {<br />
    header(&#8221;HTTP/1.1 301 Please use the canonical URI&#8221;, TRUE, 301);<br />
    header(&#8221;Location: $absoluteUri&#8221;);<br />
    header(&#8221;X-Canonical-URI: $absoluteUri&#8221;); // </code><a href="http://sebastians-pamphlets.com/x-canonical-uri-http-header/">experimental</a><code><br />
    header("Link: &lt;$absoluteUri&gt;; rel=canonical"); // experimental<br />
    exit;<br />
}<br />
</code></p>
<p>Subdomains are so 1999, also 2010 is the year of non-&#8217;.www&#8217; URIs. Keep your server name clean, uncluttered, memorable, and remarkable. By the way, you can use, alter, rewrite &#8230; the code from this pamphlet as you like. However, you must not change the <code>$canonicalServerName = "sebastians-pamphlets.com";</code> statement. I&#8217;ll appreciate the traffic. <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>When the server name is Ok, you should add some basic URI canonicalization routines here. For example add trailing slashes &#8211;if necessary&#8211;, and remove clutter from query strings.</p>
<p id="remove-google-utm-clutter-on-arrival">Sometimes even smart developers do evil things with your URIs. For example <a href="http://sebastians-pamphlets.com/thou-must-not-steal-the-trailing-slash-from-my-urls/">Yahoo truncates the trailing slash</a>. And <a href="http://sebastians-pamphlets.com/troubles-made-by-utm-variables-from-google-analytics/">Google badly messes up your URIs for click tracking purposes</a>. Here&#8217;s how you can &#8216;heal&#8217; the latter issue on arrival (after all search engine crawlers have passed the cluttered URIs to their indexers <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /> ):<code><br />$testForUriClutter = $absoluteUri;<br />
if (isset($_GET)) {<br />
   foreach ($_GET as $var => $crap) {<br />
       if ( stristr($var,&#8221;utm_&#8221;) ) {<br />
           $testForUriClutter = str_replace($testForUriClutter, &#8220;&#038;$var=$crap&#8221;, &#8220;&#8221;);<br />
           $testForUriClutter = str_replace($testForUriClutter, &#8220;&amp;amp;$var=$crap&#8221;, &#8220;&#8221;);</code><code><br />
           unset ($_GET[$var]);<br />
       }<br />
   }<br />
   $uriPartsSanitized = parse_url($testForUriClutter);<br />
   $qs = $uriPartsSanitized["query"];<br />
   $qs = str_replace($qs, "?", "");<br />
   if ("$qs" != $uriParts["query"]) {<br />
        $canonicalUri = $scheme .$canonicalServerName .$requestScript;<br />
        if (!empty($qs)) {<br />
            $canonicalUri .= "?" .$qs;<br />
        }<br />
        if (!empty($uriParts["fragment"]))      {<br />
            $canonicalUri .= "#" .$uriParts["fragment"];<br />
        }<br />
        header("HTTP/1.1 301 URI messed up by Google", TRUE, 301);<br />
        header("Location: $canonicalUri");<br />
        exit;<br />
   }<br />
}<br />
</code></p>
<p>By definition, heuristic checks barely scratch the surface. In many cases only the piece of code handling the content can catch malformed URIs that need canonicalization.</p>
<p>Also, there are many sources of malformed URIs. Sometimes a 3rd party screws a URI of yours (<a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-screwed-uris">see below</a>), but some are self-made.</p>
<p>Therefore I&#8217;d encapsulate URI canonicalization, logging pairs of bad/good URIs with referrer, script name, counter, and a lastUpdate-timestamp. Of course plain vanilla stuff like stripped www prefixes don&#8217;t need a log entry.</p>
<hr color="silver" size="1" width="150" align="left" style="margin-left:20px;margin-top:50px;" />
<p style="margin-left:20px;">Before you&#8217;re going to serve your content, do a lookup in your <a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-short-uri">shortUri</a> table. If the requested URI is a shortened URI pointing to your own stuff, don&#8217;t perform a redirect but serve the content under the shortened URI.</p>
<h3 id="sUri-impl-static-stuff">Deliver static stuff (images &#8230;)</h3>
<p>Usually your Web server checks whether a file exists or not, and sends the matching Content-type header when serving static files. Since we&#8217;ve bypassed this functionality, do it yourself:<code><br />if (empty($uriParts[&#8221;query&#8221;])) &amp;&amp; empty($uriParts[&#8221;fragment&#8221;])) &amp;&amp; file_exists(&#8221;$rootPath$requestUri&#8221;)) {<br />
    header(&#8221;Content-type: &#8221; .getContentType(&#8221;$rootPath$requestUri&#8221;), TRUE);<br />
    readfile(&#8221;$rootPath$requestUri&#8221;);<br />
    exit;<br />
}<br />
/* getContentType($filename) returns a </code><a href="http://www.iana.org/assignments/media-types/">MIME media type</a><code> like 'image/jpeg', 'image/gif', 'image/png', 'application/pdf', 'text/plain' ... but never an empty string */<br />
</code></p>
<p>If your dynamic stuff mimicks static files for some reason, and those files do exist, make sure you don&#8217;t handle them here.</p>
<p>Some files should pretend to be static, for example /robots.txt. Making use of variables like $isCrawler, $crawlerName, etc., you can use your <a href="http://sebastians-pamphlets.com/cloak-the-hell-out-of-your-robots-txt/">smart robots.txt</a> to maintain your crawler-IP database and more.</p>
<h3 id="sUri-impl-dynamic-stuff">Execute script (dynamic URI)</h3>
<p>Say you&#8217;ve a WP blog in /blog/, then you can invoke WordPress with <code><br />if (substring($requestUri, 0, 6) == &#8220;/blog/&#8221;) {<br />
require(&#8221;$rootPath/blog/index.php&#8221;);<br />
exit;<br />
}<br />
</code></p>
<p>(Perhaps the WP configuration needs a tweak to make this work.) There&#8217;s a downside, though. Passing control to WordPress disables the centralized error handling and everything else below.</p>
<p>Fortunately, when WordPress calls the <a href="http://sebastians-pamphlets.com/404/">404 page</a> (wp-content/themes/yourtheme/404.php), it hasn&#8217;t sent any output or headers yet. That means you can include the procedures discussed below in WP&#8217;s 404.php:<code><br />$httpResponseCode = &#8220;404&#8243;;<br />
$errSrc = &#8220;WordPress&#8221;;<br />
$errMsg = &#8220;The blog couldn&#8217;t make sense out of this request.&#8221;;<br />
require(&#8221;$includePath/err.php&#8221;);<br />
exit;<br />
</code></p>
<p>Like in my WordPress example, you&#8217;ll find a way to call your scripts so that they don&#8217;t need to bother with error handling themselves. Of course you need to modularize the request handler for this purpose.</p>
<h3 id="sUri-impl-short-uri">Resolve shortened URI</h3>
<p>If you&#8217;re shortening your very own URIs, then you should lookup the shortUri table for a matching $requestUri before you process static stuff and scripts. Extract the real URI belonging to your site and serve the content instead of performing a redirect.</p>
<h4 id="sUri-impl-components">Excursus: URI shortener components</h4>
<p>Using the hints below you should be able to code your own URI shortener. You don&#8217;t need all the balls and whistles (like stats) overloading most scripts available on the Web.</p>
<ul>
<li id="sUri-impl-tbl-shorturi"><b>A database table</b> with at least these attributes:</p>
<ul>
<li>shortUri.suriId, bigint, primary key, populated from a sequence (auto-increment)</li>
<li>shortUri.suriUri, text, indexed, stores the original URI</li>
<li>shortUri.suriShortcut, varchar, unique index, stores the shortcut (not the full short URI!)</li>
</ul>
<p>Storing page titles and content (snippets) makes sense, but isn&#8217;t mandatory. For outputs like &#8220;recently shortened URIs&#8221; you need a timestamp attribute.</li>
<li id="sUri-impl-create-method"><b>A method to create a shortened URI</b>.<br />
Make that an independent script callable from a Web form&#8217;s server procedure, via Ajax, SOAP, etc.</p>
<p>Without a given shortcut, use the primary key to create one. <code>base_convert(intval($suriId), 10, 36);</code> converts an integer into a short string. If you can&#8217;t do that in a database insert/create trigger procedure, retrieve the primary key&#8217;s value with <code>LAST_INSERT_ID()</code> or so and perform an update.</p>
<p>URI shortening is bad enough, hence it makes no sense to maintain more than one short URI per original URI. Your <i>create short URI</i> method should return a previously created shortcut then.</p>
<p>If you&#8217;re storing titles and such stuff grabbed from the destination page, don&#8217;t fetch the destination page on create. Better do that when you actually need this information, or run a cron job for this purpose.</p>
<p>With the shortcut returned build the short URI on-the-fly <code>$shortUri = getBaseUri() ."/" .$suriShortcut;</code> (so you can use your URI shortener across all your sites). </li>
<li id="sUri-impl-retrieve-method"><b>A method to retrieve the original URI</b>.<br />
Remove the leading slash (and other ballast like a useless query string/fragment) from REQUEST_URI and pull the shortUri record identified by suriShortcut.</p>
<p>Bear in mind that shortened URIs spread via social media do get abused. A shortcut like &#8216;xxyyzz&#8217; can appear as &#8216;xxyyz..&#8217;, &#8216;xxy&#8217;, and so on. So if the path component of a REQUEST_URI somehow looks like a shortened URI, you should try a broader query. If it returns one single result, use it. Otherwise display an <a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-error-page">error page</a> with <a href="http://tag.us.com/_sur...yadayadayada" title="Example from an experimental site, not exactly perfect">suggestions</a>.</li>
<li id="sUri-impl-suri-maint"><b>A Web form to create and edit shortened URIs</b>.<br />
Preferably protected in a site admin area. At least for your own URIs you should use somewhat meaningful shortcuts, so make suriShortcut an input field.
</li>
<li id="sUri-impl-api">If you want to use your URI shortener with a Twitter client, then build an <a href="http://code.google.com/p/bitly-api/wiki/ApiDocumentation">API</a>.
</li>
<li id="sUri-impl-click-stats">If you need particular stats for your short URIs pointing to foreign sites that your analytics package can&#8217;t deliver, then store those click data separately.<br />
<code>// end excursus</code>
</li>
</ul>
<p>If REQUEST_URI contains a valid shortcut belonging to a foreign server, then do a 301 redirect.<code><br />$suriUri = resolveShortUri($requestUri);<br />
if ($suriUri === FALSE) {<br />
    $httpResponseCode = &#8220;404&#8243;;<br />
    $errSrc = &#8220;sUri&#8221;;<br />
    $errMsg = &#8220;Invalid short URI. Shortcut resolves to more than one result.&#8221;;<br />
    require(&#8221;$includePath/err.php&#8221;);<br />
    exit;<br />
}<br />
if (!empty($suriUri))<br />
    if (!stristr($suriUri, $canonicalServerName)) {<br />
        header(&#8221;HTTP/1.1 301 Here you go&#8221;, TRUE, 301);<br />
        header(&#8221;Location: $suriUri&#8221;);<br />
        exit;<br />
    }<br />
}<br />
</code></p>
<p>Otherwise ($suriUri is yours) deliver your content without redirecting.</p>
<h3 id="sUri-impl-redirect">Redirect to destination (invalid request)</h3>
<p id="sUri-impl-screwed-uris">From reading your raw logs (404 stats don&#8217;t cover 302-Found crap) you&#8217;ll learn that some of your resources get persistently requested with invalid URIs. This happens when someone links to you with a messed up URI. It doesn&#8217;t make sense to show visitors following such a link your 404 page.</p>
<p>Most screwed URIs are unique in a way that they still &#8216;address&#8217; one particular resource on your server. You should <a href="http://sebastians-pamphlets.com/getting-the-most-out-of-googles-404-stats/">maintain a mapping table</a> for all identified screwed URIs, pointing to the canonical URI. When you can identify a resouce from a lookup in this mapping table, then do a 301 redirect to the canonical URI.</p>
<p>When you feature a &#8220;product of the week&#8221;, &#8220;hottest blog post&#8221;, &#8220;today&#8217;s joke&#8221; or so, then bookmarkers will love it when its URI doesn&#8217;t change. For such transient URIs do a 307 redirect to the currently featured page. Don&#8217;t fear non-existing &#8216;duplicate content penalties&#8217;. Search engines are smart enough to figure out your intention. Even if the transient URI outranks the original page for a while, you&#8217;ll still get the SERP traffic you deserve.</p>
<h3 id="sUri-impl-guess-uri">Guess destination (invalid request)</h3>
<p>For many <a href="http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/#sUri-impl-screwed-uris">screwed URIs</a> you can identify the canonical URI on-the-fly. REQUEST_URI and HTTP_REFERER provide lots of hints, for example keywords from SERPs or fragments of existing URIs.</p>
<p>Once you&#8217;ve identified the destination, do a 307 redirect and log both REQUEST_URI and guessed destination URI for a later review. Use these logs to update your <i>screwed URIs mapping table</i> (see above).</p>
<p>When you can&#8217;t identify the destination free of doubt, and the visitor comes from a search engine, extract the search query from the HTTP_REFERER and pass it to your site search facility (strip operators like site: and inurl:). Log these requests as invalid, too, and update your mapping table.</p>
<h3 id="sUri-impl-error-page">Serve a useful error page</h3>
<p>Following the suggestions above, you got rid of most reasons to actually show the visitor an error page. However, make your 404 page useful. For example don&#8217;t bounce out your visitor with a prominent error message in 24pt or so. Of course you should mention that an error has occured, but your error page&#8217;s prominent message should consist of hints how the visitor can reach the estimated contents.</p>
<p>A central error page gets invoked from various scripts. Unfortunately, err.php can&#8217;t be sure that none of these scripts has outputted something to the user. With a previous output of just one single byte you can&#8217;t send an HTTP response header. Hence prefix the header() statement with a &#8216;@&#8217; to supress PHP error messages, and catch and log errors.</p>
<p>Before you output your wonderful error page, send a 404 header:<code><br />if ($httpResponseCode == NULL) {<br />
    $httpResponseCode = &#8220;404&#8243;;<br />
}<br />
if (empty($httpResponseCode)) {<br />
    $httpResponseCode = &#8220;501&#8243;; // log for debugging<br />
}<br />
@header(&#8221;HTTP/1.1 $httpResponseCode Shit happens&#8221;, TRUE, intval($httpResponseCode));<br />
logHeaderErr(error_get_last());<br />
</code></p>
<p>In rare cases you better send a 410-Gone header, for example when Matt&#8217;s team has discovered a shitload of questionable pages and you&#8217;ve filed a reconsideration request.</p>
<p>In general, do avoid 404/410 responses. Every URI indexed anywhere is an asset. Closely watch your 404 stats and try to map these requests to related content on your site.</p>
<p>Use possible input ($errSrc, $errMsg, &#8230;) from the caller to customize the error page. Without meaningful input, deliver a generic error page. A search for [<a href="http://www.google.com/search?hl=en&#038;num=100&#038;q=best+404+page+ever">* 404 page *</a>] might inspire you (<a href="http://yoast.com/404-error-pages-wordpress/">WordPress users click here</a>). </p>
<hr align="center" color="silver" size="1" width="150" style="margin-top:70px;" />
<p>All errors are mine. In other words, be careful when you grab my untested code examples. It&#8217;s all dumped from memory without further thoughts and didn&#8217;t face a syntax checker.</p>
<p>I consider this pamphlet kinda draft of a concept, not a design pattern or tutorial. It was fun to write, so go get the best out of it. I&#8217;d be happy to discuss your thoughts in the comments. Thanks for your time.</p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/", "style": "big", "title": "How to cleverly integrate your own URI shortener" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/http-request-handler-with-integrated-short-uri-support/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The anatomy of a deceptive Tweet spamming Google Real-Time Search</title>
		<link>http://sebastians-pamphlets.com/how-to-spam-google-real-time-search-via-twitter/</link>
		<comments>http://sebastians-pamphlets.com/how-to-spam-google-real-time-search-via-twitter/#comments</comments>
		<pubDate>Thu, 10 Dec 2009 10:12:44 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Webspam]]></category>

		<category><![CDATA[Search Quality]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[Internet Marketing]]></category>

		<category><![CDATA[Spam]]></category>

		<category><![CDATA[Twitter]]></category>

		<category><![CDATA[SEO]]></category>

		<category><![CDATA[Cloaking]]></category>

		<category><![CDATA[Crap]]></category>

		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/how-to-spam-google-real-time-search-via-twitter/</guid>
		<description><![CDATA[
Minutes after the launch of Google&#8217;s famous Real Time Search, the Internet marketing community began to spam the scrolling SERPs. Google gave birth to a new spam industry.
I&#8217;m sure Google&#8217;s WebSpam team will pull the plug sooner or later, but as of today Google&#8217;s real time search results are extremely vulnerable to questionable content.
The somewhat [...]]]></description>
			<content:encoded><![CDATA[
<p><img  src="http://sebastians-pamphlets.com/img/posts/spamming-google-real-time-search.png" width="250" height="345" align="right" style="margin-left:5px;" alt="Google real time search spammed and abused" title=""  />Minutes after the <a href="http://googleblog.blogspot.com/2009/12/relevance-meets-real-time-web.html?utm_source=sebastian&#038;utm_medium=pamphlet&#038;utm_campaign=thou+shalt+not+fuck+with+my+uris">launch</a> of Google&#8217;s <a href="http://searchengineland.com/search-real-time-madness-31668">famous</a> Real Time Search, the Internet marketing community <a href="http://sphinn.com/story/135685">began</a> to <a href="http://outspokenmedia.com/seo/google-real-time-spam/">spam</a> the <a href="http://www.google.com/search?hl=en&#038;safe=off&#038;esrch=RTSearch&#038;tbo=1&#038;num=100&#038;q=spam&#038;tbs=rltm:1">scrolling SERPs</a>. Google gave birth to a <a href="http://www.seo-theory.com/2009/12/07/google-launches-a-new-spam-industry/">new spam industry</a>.</p>
<p>I&#8217;m sure Google&#8217;s <a href="http://friendfeed.com/dannysullivan/d973e438/real-time-spam-google-says-been-fighting-so-long">WebSpam</a> team will pull the plug sooner or later, but as of today Google&#8217;s real time search results are extremely vulnerable to questionable content.</p>
<p>The somewhat shady approach to make creative use of real time search I&#8217;m outlining below will not work forever. It can be used for really evil purposes,  and Google is aware of the problem. Frankly, if I&#8217;d be the Googler in charge, I&#8217;d dump the whole real-time thingy until the spam defense lines are rock solid.</p>
<p id="rtss-recipe"><strong>Here&#8217;s the recipe from Dr Evil&#8217;s WebSpam-Cook-Book:</strong></p>
<h3 id="rtss-ingredients">Ingredients</h3>
<ul>
<li>1 <a href="http://www.google.com/trends?q=spam+google">popular topic</a> that pulls lots of searches, but not so many that the results scroll down too fast.</li>
<li>1 <a href="http://www.google.com/products?q=spam+google&#038;hl=en&#038;aq=f">landing page</a> that makes the punter pull out the plastic in no time.</li>
<li>1 <a href="http://www.google.com/support/webmasters/bin/answer.py?hl=en&#038;answer=93713">trusted authority page</a> totally lacking commercial intentions. View its source code, it must have a valid TITLE element with an appealing call for action related to your topic in its HEAD section.</li>
<li>1 <a href="http://goo.gl/">short</a> domain, 1 cheap Web hosting plan (Apache, PHP), 1 plain text editor, 1 FTP client, 1 Twitter account, and a prize basic coding skills.</li>
</ul>
<h3 id="rtss-preparation">Preparation</h3>
<p>Create a new text file and name it <code>hot-topic.php</code> or so. Then code:<code><br />
&lt;?php<br />
$landingPageUri = "http://affiliate-program.com/?your-aff-id";<br />
$trustedPageUri = "http://google.com/something.py";<br />
if (stristr($_SERVER["HTTP_USER_AGENT"], "Googlebot")) {<br />
   header("HTTP/1.1 307 Here you go today", TRUE, 307);<br />
   header("Location: $trustedPageUri");<br />
}<br />
else {<br />
   header("HTTP/1.1 301 Happy shopping", TRUE, 301);<br />
   header("Location: $landingPageUri");<br />
}<br />
exit;<br />
?&gt;</code></p>
<p>Provided you&#8217;re a savvy spammer, your crawler detection routine will be a little more <a href="http://fantomaster.com/fasvsspy01.html">complex</a>.</p>
<p>Save the file and upload it, then test the URI <code>http://youspamaw.ay/hot-topic.php</code> in your browser.</p>
<h3 id="rtss-serving">Serving</h3>
<ul>
<li>Login to Twitter and submit lots of nicely crafted, not too much keyword stuffed messages carrying your spammy URI. Do not use obscene language, e.g. don&#8217;t swear, and sail around phrases like &#8216;buy cheap viagra&#8217; with synonyms like &#8216;brighten up your girl friend&#8217;s romantic moments&#8217;.</li>
<li>On their SERPs, Google will display the text from the trusted page&#8217;s TITLE element, linked to your URI that leads punters to a sales pitch of your choice.</li>
<li>Just for entertainment, closely monitor Google&#8217;s real time SERPs, and your real-time sales stats as well.</li>
<li>Be happy and get rich by end of the week.</li>
</ul>
<p>Google removes links to untrusted destinations, that&#8217;s why you need to abuse authority pages. As long as you don&#8217;t launch f-bombs, Google&#8217;s profanity filters make flooding their real time SERPs with all sorts of crap a breeze.</p>
<p>Hey <a href="http://twitter.com/GoogleWebspam">Google</a>, for the sake of our children, take that as a spam report!</p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/how-to-spam-google-real-time-search-via-twitter/", "style": "big", "title": "The anatomy of a deceptive Tweet spamming Google Real-Time Search" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/how-to-spam-google-real-time-search-via-twitter/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How to borrow relevance from authority pages with 307 redirects</title>
		<link>http://sebastians-pamphlets.com/how-to-steal-relevancy-with-307-redirects-no-longer/</link>
		<comments>http://sebastians-pamphlets.com/how-to-steal-relevancy-with-307-redirects-no-longer/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 18:13:28 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[Webspam]]></category>

		<category><![CDATA[Webmaster Central]]></category>

		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/how-to-steal-relevancy-with-307-redirects-no-longer/</guid>
		<description><![CDATA[
Every once in a while I switch to Dr Evil mode. That&#8217;s a &#8220;do more evil&#8221; type of pamphlet. Don&#8217;t bother reading the disclaimer, just spam away &#8230;
Why the heck should you invest valuable time into crafting out compelling content, when there&#8217;s a shortcut?
There are so many awesome Web pages out there, just pick some [...]]]></description>
			<content:encoded><![CDATA[
<p>Every once in a while I switch to Dr Evil mode. That&#8217;s a &#8220;do more evil&#8221; type of pamphlet. Don&#8217;t bother reading the disclaimer, just spam away &#8230;</p>
<p><img src="http://sebastians-pamphlets.com/img/posts/steal-relecanvy-with-307-redirects.png" with="200" height="174" style="margin-left:5px;" align="right" alt="Content theft with 307 redirects" title="" />Why the heck should you invest valuable time into crafting out <a href="http://sebastians-pamphlets.com/dont-underestimate-the-truth-in-se-quality-guidelines/">compelling content</a>, when there&#8217;s a shortcut?</p>
<p>There are so many awesome Web pages out there, just pick some and steal their content. You say &#8220;duplicate content issues&#8221;, I say &#8220;don&#8217;t worry&#8221;. You say &#8220;copyright violation&#8221;, I say &#8220;be happy&#8221;. Below I explain the setup.</p>
<p>This somewhat shady <acronym title="Internet Marketing">IM</acronym> technique is for you when you&#8217;re shy of automatted content generation.</p>
<p>Register a new (short!) domain and create a tiny site with a few pages of totally unique and somewhat interesting content. Write opinion pieces, academic papers or whatnot, just don&#8217;t use content generators or anything that cannot pass a human bullshit detector. No advertising. No questionable links. Instead, link out to authority pages. No SEO stuff like nofollow&#8217;ed links to imprints or so.</p>
<p>Launch with a few links from clean pages. Every now and then drop a deep link in relevant discussions on forums or social media sites. Let the search engines become familiar with your site. That&#8217;ll attract even a few natural inbound links, at least if your content is linkworthy.</p>
<p>Use <a href="http://google.com/webmasters/">Google&#8217;s Webmaster Console</a> (GWC) to monitor your progress. Once all URIs from your sitemap are indexed and show in [site:yourwebspam.com] searches, begin to expand your site&#8217;s menu and change outgoing links to authority pages embedded in your content.</p>
<p>Create short URIs (LE 20 characters!) that point to authority pages. Serve search engine crawlers a <a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#307-temporary-redirect">307</a>, and human surfers a <a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#301-moved-permanently">301</a> redirect. Build deep links to those URIs, for example in tweets. Once you&#8217;ve gathered 1,000+ inbounds, you&#8217;ll receive SERP traffic. By the way, don&#8217;t buy the sandbox myths.</p>
<p>Watch the <i>keywords</i> page in you GWC account. It gets populated with keywords that appear only in content of pages you&#8217;ve hijacked with redirects. Watch your [site:yourwebspam.com] SERPs. Usually the top 10 keywords listed in the GWC report will originate from pages listed on the first [site:yourwebspam.com] SERPs, provided you&#8217;ve hijacked awesome content.</p>
<p>Add (new) keywords from pages that appear both in redirect destinations listed within the first 20 [site:yourwebspam.com] search results, as well as in the first 20 listed keywords, to articles you actually serve on your domain.</p>
<p>Detect SERP referrers (human surfers who&#8217;ve clicked your URIs on search result pages) and redirect those to sales pitches. That goes for content pages as well as for redirecting URIs (mimiking <a href="http://sebastians-pamphlets.com/links/categories/?cat=s-url">shortened URIs</a>). Laugh all the way to the bank.</p>
<p>Search engines rarely will discover your scam. Of course shit happens, though. Once the domain is burned, just block crawlers, redirect everything else to your sponsors, and let the domain expire.</p>
<p><img src="http://sebastians-pamphlets.com/img/posts/307-content-theft-is-history.png" with="150" height="119" style="margin-left:5px;" align="right" alt="History: Content theft with 307 redirects" title="" /><b>Disclaimer:</b> Google has put an end to most 307 spam tactics. That&#8217;s why I&#8217;m publishing all this crap. Because watching decreasing traffic to spammy sites is frustrating. Deceptive 307&#8242;ing URIs won&#8217;t rank any more. Slowly, actually very slow, GWC reports follow suit.</p>
<p>What can we learn? Do not believe in the truth of search engine reports. Just because Google&#8217;s webmaster console tells you that Google thinks a keyword is highly relevant to your site, that doesn&#8217;t mean you&#8217;ll rank for it on their SERPs. Most probably GWC is not the average search engine spammer&#8217;s tool of the trade.</p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/how-to-steal-relevancy-with-307-redirects-no-longer/", "style": "big", "title": "How to borrow relevance from authority pages with 307 redirects" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/how-to-steal-relevancy-with-307-redirects-no-longer/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Search engines should make shortened URIs somewhat persistent</title>
		<link>http://sebastians-pamphlets.com/dear-search-engines-please-rescue-our-shortened-urls/</link>
		<comments>http://sebastians-pamphlets.com/dear-search-engines-please-rescue-our-shortened-urls/#comments</comments>
		<pubDate>Wed, 07 Oct 2009 17:29:26 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Social Web]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[MSN]]></category>

		<category><![CDATA[URI shortening]]></category>

		<category><![CDATA[Twitter]]></category>

		<category><![CDATA[Risky Linkage]]></category>

		<category><![CDATA[Yahoo]]></category>

		<category><![CDATA[SEO]]></category>

		<category><![CDATA[Crap]]></category>

		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/dear-search-engines-please-rescue-our-shortened-urls/</guid>
		<description><![CDATA[
URI shorteners are crap. Each and every shortened URI expresses a design flaw. All &#8211;or at least most&#8211; public URI shorteners will shut down sooner or later, because shortened URIs are hard to monetize. Making use of 3rd party URI shorteners translates to &#8220;put traffic at risk&#8221;. Not to speak of link love (PageRank, Google [...]]]></description>
			<content:encoded><![CDATA[
<p><a href="http://tag.us.com/uri-shorteners-suck-ass.htm">URI shorteners are crap</a>. Each and every shortened URI expresses a design flaw. All &#8211;or at least most&#8211; public URI shorteners will shut down sooner or later, because shortened URIs are hard to monetize. Making use of 3rd party URI shorteners translates to &#8220;put traffic at risk&#8221;. Not to speak of link love (PageRank, Google juice, link popularity) lost forever.</p>
<p><img src="http://sebastians-pamphlets.com/img/posts/se-rescue-short-url.png" width="250" height="222" align="right" alt="SEs could rescue tiny URLs" title="Dear search engines, please make our shortened URIs persistent!" style="margin-left:3px;" />Search engines could provide a way out of the <strong>sURL dilemma</strong> that Twitter &amp; Co created with their crappy, thoughtless and shortsighted software designs. Here&#8217;s how:</p>
<p>Most browsers support search queries in the address bar, as well as suggestions (aka search results) on DNS errors, and sometimes even 404s or other HTTP response codes other than 200/3x. That means browsers &#8220;ask a search engine&#8221; when an HTTP request fails.</p>
<p>When a <acronym title="Top Level Domain, that's .com/.net/.org...">TLD</acronym> is out of service, search engines could have crawled a 301 or meta refresh from a page formerly living on a <code>.yu</code> domain for example. They know the new address and can lead the user to this (working) URI.</p>
<p>The same goes for shortened URIs created ages ago by URI shortening services that died in the meantime. Search engines have transferred all the link juice from the shortened URI to the destination page already, so why not point users that request a dead <i>short URI</i> to the right destination?</p>
<p>Search engines have all the data required for rescuing short URIs that are out of service in their datebases. Not de-indexing &#8220;outdated&#8221; URIs belonging to URI shorteners would be a minor tweak. At least Google has stored attributes and behavior of all links on the Web since the past century, and most probably other search engines are operated by data rats too.</a></p>
<p>URI shorteners can be identified by simple patterns. They gather tons of inbound links from foreign domains that get redirected (not always using a 301!) to URIs on other 3rd party domains. Of course that applies to some AdServers too, but rest assured search engines do know the differences.</p>
<p><strong>So why the heck didn&#8217;t Google, <strike>Yahoo/MSN</strike> Bing, and Ask offer such a service yet? I thought it&#8217;s all about users, but I might have misread something. Sigh.</strong></p>
<p><small>By the way, I&#8217;ve recorded search engine misbehavior with regard to shortened URIs that could arouse Jack The Ripper, but that&#8217;s a completely other story.</small></p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/dear-search-engines-please-rescue-our-shortened-urls/", "style": "big", "title": "Search engines should make shortened URIs somewhat persistent" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/dear-search-engines-please-rescue-our-shortened-urls/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Debugging robots.txt with Google Webmaster Tools</title>
		<link>http://sebastians-pamphlets.com/debugging-robots-txt-with-google-webmaster-tools/</link>
		<comments>http://sebastians-pamphlets.com/debugging-robots-txt-with-google-webmaster-tools/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 17:32:01 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Crawler Directives]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[Webmaster Central]]></category>

		<category><![CDATA[robots.txt]]></category>

		<category><![CDATA[SEO]]></category>

		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/debugging-robots-txt-with-google-webmaster-tools/</guid>
		<description><![CDATA[
Although Google&#8217;s Webmaster Console is a really neat toolkit, it can mislead the not-that-savvy crowd every once in a while.
When you go to &#8220;Diagnostics::Crawl Errors::Restricted by robots.txt&#8221; and you find URIs that aren&#8217;t disallow&#8217;ed or even noindex&#8217;ed in your very own robots.txt, calm down.
Google&#8217;s cool robots.txt validator withdraws its knowledge of redirects and approves your [...]]]></description>
			<content:encoded><![CDATA[
<p>Although <a href="http://webmasters.google.com/">Google&#8217;s Webmaster Console</a> is a really neat toolkit, it can mislead the not-that-savvy crowd every once in a while.</p>
<p>When you go to &#8220;Diagnostics::Crawl Errors::Restricted by robots.txt&#8221; and you find URIs that aren&#8217;t disallow&#8217;ed or even noindex&#8217;ed in your very own robots.txt, calm down.</p>
<p>Google&#8217;s cool robots.txt validator withdraws its knowledge of redirects and approves your redirecting URIs, driving you nuts until you <a href="http://www.seoconsultants.com/tools/headers/">check each URI&#8217;s HTTP response code</a> for <a href="http://sebastians-pamphlets.com/links/categories/?cat=redirects">redirects</a> (<a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/">HTTP response codes 301, 302 and 307</a>, as well as <a href="http://sebastians-pamphlets.com/google-and-yahoo-treat-undelayed-meta-refresh-as-301-redirect/">undelayed meta refreshs</a>).</p>
<p>Google obeys robots.txt even in a chain of redirects. If for Google&#8217;s user agent(s) an URI given in an HTTP header&#8217;s <code>location</code> is disallow&#8217;ed or noindex&#8217;ed, Googlebot doesn&#8217;t fetch it, regardless the position in the current chain of redirects. Even a robots.txt block in the 5th hop stops the greedy Web robot. Those URIs are correctly reported back as &#8220;restricted by robots.txt&#8221;, Google just refuses to tell you that the blocking crawler directive origins from a foreign server.</p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/debugging-robots-txt-with-google-webmaster-tools/", "style": "big", "title": "Debugging robots.txt with Google Webmaster Tools" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/debugging-robots-txt-with-google-webmaster-tools/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Upgrading from IIS/ASP to Apache/PHP</title>
		<link>http://sebastians-pamphlets.com/how-to-migrate-a-website-from-iis-asp-to-apache-php/</link>
		<comments>http://sebastians-pamphlets.com/how-to-migrate-a-website-from-iis-asp-to-apache-php/#comments</comments>
		<pubDate>Tue, 11 Dec 2007 20:47:25 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[404grabber]]></category>

		<category><![CDATA[Duplicate Content]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[Web development]]></category>

		<category><![CDATA[Copy+Paste-Penalties]]></category>

		<category><![CDATA[.htaccess]]></category>

		<category><![CDATA[IIS]]></category>

		<category><![CDATA[SEO]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/how-to-migrate-a-website-from-iis-asp-to-apache-php/</guid>
		<description><![CDATA[
Once you&#8217;re sick of IIS/ASP maladies you want to upgrade your Web site to utilize standardized technologies and reliable OpenSource software. On an Apache Web server with PHP your .asp scripts won&#8217;t work, and you can&#8217;t run MS-Access &#8220;databases&#8221; and such stuff under Apache. 
Here is my idea of a smoothly migration from IIS/ASP to [...]]]></description>
			<content:encoded><![CDATA[
<p><img src="http://sebastians-pamphlets.com/img/posts/upgrade-from-iis-asp-to-apache-php.png" width="250" height="227" align="right" style="margin-left:4px;" alt="Upgrade from Windows/IIS/ASP to Unix/Apache/PHP" title="Get the most out of your Web site - throw away Windows/IIS/ASP!"  />Once you&#8217;re sick of IIS/ASP maladies you want to upgrade your Web site to utilize standardized technologies and reliable OpenSource software. On an Apache Web server with PHP your .asp scripts won&#8217;t work, and you can&#8217;t run MS-Access &#8220;databases&#8221; and such stuff under Apache. </p>
<p>Here is my idea of a smoothly migration from IIS/ASP to Apache/PHP. Grab any Unix box from your hoster&#8217;s portfolio and start over.</p>
<p>(Recently I got a tiny IIS/ASP site about <a href="http://link-condom.com/">uses &amp; abuses of link condoms</a> and moved it to an Apache server. I&#8217;m well known for brutal IIS rants, but so far I didn&#8217;t discuss a way out of such a dilemma, so I thought blogging this move could be a good idea.) </p>
<p>I don&#8217;t want to make this piece too complex, so I skip database and code migration strategies. Read Mike Hillyer&#8217;s article <a href="http://dev.mysql.com/tech-resources/articles/migrating-from-microsoft.html">Migrating from Microsoft Access/MS-SQL to MySQL</a>, and try tools like <a href="http://asp2php.naken.cc/docs.php">ASP to PHP</a>. (With my tiny <a href="http://link-condom.com/about.asp">link condom</a> site I overwrote the ASP code with PHP statements in my primitive text editor.)</p>
<p><b>From an SEO perspective such an upgrade comes with pitfalls:</b>
<ul>
<li>Changing file extensions from .asp to .php is not an option. We want to keep the number of unavoidable redirects as low as possible.</li>
<li>Default.asp is usually not configured as a valid default document under Apache, hence requests of http://example.com/ run into 404 errors.</li>
<li>Basic server name canonicalization routines (www vs. non-www) from ASP scripts are not convertible.</li>
<li>IIS-URIs are not case sensitive, that means that /Default.asp will 404 on Apache when the filename is /default.asp. Usually there are lowercase/uppercase issues with query string variables and values as well.</li>
<li>Most probably search engines have URL variants in their indexes, so we want to adapt their URL canonicalization, at least where possible.</li>
<li>HTML editors like Microsoft Visual Studio tend to duplicate the HTML code of templated page areas. Instead of editing menus or footers in all scripts we want to encapsulate them.</li>
<li>If the navigation makes use of relative links, we need to convert those to absolute URLs.</li>
<li>Error handling isn&#8217;t convertible. Improper error handling can cause decreasing search engine traffic.</li>
</ul>
<h3>Running /default.asp, /home.asp etc. as PHP scripts</h3>
<p>When you upload an .asp file to an Apache Web server, most user agents can&#8217;t handle it. Browsers treat them as unknown file types and force downloads instead of rendering them. Next those files aren&#8217;t parsed for PHP statements, provided you&#8217;ve rewritten the ASP code already.</p>
<p>To tell Apache that .asp files are valid PHP scripts outputting X/HTML, add this code to your server config or your .htaccess file in the root: <code><b><br />
AddType text/html .asp<br />
AddHandler application/x-httpd-php .asp </b></code><br />
The first line says that .asp files shall be treated as HTML documents, and should force the server to send a <code>Content-Type: text/html</code> HTTP header. The second line tells Apache that it must parse .asp files for PHP code. </p>
<p>Just in case the AddType statement above doesn&#8217;t produce a <code>Content-Type: text/html</code> header, here is another way to tell all user agents requesting .asp files from your server that the content type for .asp is text/html. If you&#8217;ve mod_headers available, you can accomplish that with this .htaccess code: <code><b><br />
&lt;IfModule mod_headers.c&gt;<br />
SetEnvIf Request_URI \.asp is_asp=is_asp<br />
Header set &quot;Content-type&quot; &quot;text/html&quot; env=is_asp<br />
Header set imagetoolbar &quot;no&quot;<br />
&lt;/IfModule&gt; </b></code><br />
(The imagetoolbar=no header tells IE to behave nicely; you can use this directive in a meta tag too.)<br />
If for some reason mod_headers doesn&#8217;t work well with mod_setenvif, giving 500 error codes or so, then you can set the content-type with PHP too. Add this to a PHP script file which is included in all your scripts at the very top: <code><b><br />
@header(&quot;Content-type: text/html&quot;, TRUE);  </b></code><br />
Instead of &#8220;text/html&#8221; alone, you can define the character set too: &#8220;text/html; charset=UTF-8&#8243;</p>
<h3>Sanitizing the home page URL by eliminating &#8220;default.asp&#8221;</h3>
<p>Instead of slowing down Apache by defining just another default document name (<code>DirectoryIndex index.html index.shtml index.htm index.php [...] default.asp</code>), we get rid of &#8220;/default.asp&#8221; with this &#8220;/index.php&#8221; script: <code><b><br />
&lt;?php<br />
@require(&quot;default.asp&quot;);<br />
?&gt; </b></code><br />
Now every request of http://example.com/ executes /index.php which includes /default.asp. This works with subdirectories too.</p>
<p>Just in case someone requests /default.asp directly (search engines keep forgotten links!), we perform a permanent redirect in .htaccess: <code><b><br />
Redirect 301 /default.asp http://example.com/<br />
Redirect 301 /Default.asp http://example.com/ </b></code></p>
<h3>Converting the ASP code for server name canonicalization</h3>
<p>If you find ASP canonicalization routines like <code><b><br />
&lt;%@ Language=VBScript %&gt;<br />
&lt;%<br />
if strcomp(Request.ServerVariables(&quot;SERVER_NAME&quot;), &quot;www.example.com&quot;, vbCompareText) = 0 then<br />
   Response.Clear<br />
   Response.Status = &quot;301 Moved Permanently&quot;<br />
   strNewUrl = Request.ServerVariables(&quot;URL&quot;)<br />
   if instr(1,strNewUrl, &quot;/default.asp&quot;, vbCompareText) &gt; 0 then<br />
     strNewUrl = replace(strNewUrl, &quot;/Default.asp&quot;, &quot;/&quot;)<br />
     strNewUrl = replace(strNewUrl, &quot;/default.asp&quot;, &quot;/&quot;)<br />
   end if<br />
   if Request.QueryString &lt;&gt; &quot;&quot; then<br />
       Response.AddHeader &quot;Location&quot;,&quot;http://example.com&quot; &amp; strNewUrl &amp; &quot;?&quot; &amp; Request.QueryString<br />
   else<br />
       Response.AddHeader &quot;Location&quot;,&quot;http://example.com&quot; &amp; strNewUrl<br />
   end if<br />
   Response.End<br />
end if<br />
%&gt;  </b></code><br />
(or the other way round) at the top of all scripts, just select and delete. This .htaccess code works way better, because it takes care of other server name garbage too: <code><b><br />
RewriteEngine On<br />
RewriteCond %{HTTP_HOST} !^example\.com [NC]<br />
RewriteRule (.*) http://example.com/$1 [R=301,L] </b></code><br />
(you need mod_rewrite, that&#8217;s usually enabled with the default configuration of Apache Web servers). </p>
<h3>Fixing case issues like /script.asp?id=value vs. /Script.asp?ID=Value</h3>
<p>Probably a M$ developer didn&#8217;t read more than the scheme and server name chapter of the URL/URI standards, at least I&#8217;ve no better explanation for the fact that these clowns made the path and query string segment of URIs case-insensitive. (Ok, I have an idea, but nobody wants to read about M$ world domination plans.)</p>
<p>Just because &#8211;contrary to Web standards&#8211; M$ finds it funny to serve the same contents on request of /Home.asp as well as /home.ASP, such crap doesn&#8217;t fly on the World Wide Web. Search engines &#8211;and other Web services which store URLs&#8211; treat them as different URLs, and consider everything except one version duplicate content.</p>
<p>Creating hyperlinks in HTML editors by picking the script files from the Windows Explorer can result in HREF values like &#8220;/Script.asp&#8221;, although the file itself is stored with an all-lowercase name, and the FTP client uploads &#8220;/script.asp&#8221; to the Web server. There are more ways to fuck up file names with improper use of (leading) uppercase characters. Typos like that are somewhat undetectable with IIS, because the developer surfing the site won&#8217;t get 404-Not found responses. </p>
<p>Don&#8217;t misunderstand me, you&#8217;re free to camel-case file names for improved readability, but then make sure that the file system&#8217;s notation matches the URIs in HREF/SRC values. (Of course hyphened file names like &#8220;buy-cheap-viagra.asp&#8221; top the CamelCased version &#8220;BuyCheapViagra.asp&#8221; when it comes to search engine rankings, but don&#8217;t freak out about keywords in URLs, that&#8217;s ranking factor #202 or so.)</p>
<p>Technically spoken, converting all file names, variable names and values as well to all-lowercase is the simplest solution. This way it&#8217;s quite easy to 301-redirect all invalid requests to the canonical URLs. </p>
<p>However, each redirect puts search engine traffic at risk. Not all search engines process 301 redirects as they should (<a href="http://sphinn.com/story/16345">MSN Live Search</a> for example doesn&#8217;t follow permanent redirects and doesn&#8217;t pass the reputation earned by the old URL over to the new URL). So if you&#8217;ve good SERP positions for &#8220;misspelled&#8221; URLs, it might make sense to stick with ugly directory/file names. Check your search engine rankings, perform [site:example.com] search queries on all major engines, and read the SERP referrer reports from the old site&#8217;s server stats to identify all URLs you don&#8217;t want to redirect. By the way, the link reports in <a href="http://www.google.com/webmasters/tools/">Google&#8217;s Webmaster Console</a> and <a href="http://siteexplorer.search.yahoo.com/">Yahoo&#8217;s Site Explorer</a> reveal invalid URLs with (internal as well as external) inbound links too.</p>
<p>Whatever strategy fits your needs best, you&#8217;ve to call a script handling invalid URLs from your .htaccess file. You can do that with the ErrorDocument directive: <code><b><br />
ErrorDocument 404 /404handler.php </b></code><br />
That&#8217;s safe with static URLs without parameters and should work with dynamic URIs too. When you &#8211;in some cases&#8211; deal with query strings and/or virtual URIs, the .htaccess code becomes more complex, but handling virtual paths and query string parameters in the PHP scripts might be easier: <code><b><br />
&lt;IfModule mod_rewrite.c&gt;<br />
RewriteEngine On<br />
RewriteBase /<br />
RewriteCond %{REQUEST_FILENAME} !-f<br />
RewriteCond %{REQUEST_FILENAME} !-d<br />
RewriteRule . /404handler.php [L]<br />
&lt;/IfModule&gt; </b></code><br />
In both cases Apache will process /404handler.php if the requested URI is invalid, that is if the path segment (/directory/file.extension) points to a file that doesn&#8217;t exist.</p>
<p>And here is the PHP script /404handler.php:<br />
<b><a onclick="showContent('php-code-404-handler'); return false;">View</a>|<a onclick="hideContent('php-code-404-handler'); return false;">hide</a> PHP code.</b> (If you&#8217;ve disabled JavaScript you can&#8217;t grab the PHP source code!)<code id="php-code-404-handler" style="display:none;"><b><br />
&lt;?php // 404handler.php<br />
      // called from .htaccess if the requested path doesn&#8217;t exist<br />
&nbsp;<br />
$thisFileName    = &quot;404handler.php&quot;;  // change this<br />
$canonicalScheme = &quot;http://&quot;;<br />
$canonicalServer = &quot;example.com&quot;; // change this<br />
$errorPageUri    = &quot;/error.asp&quot;;  // change this<br />
$documentRoot    = $_SERVER[&quot;DOCUMENT_ROOT&quot;];<br />
$requestUri      = $_SERVER[&quot;REQUEST_URI&quot;];<br />
$canonicalUri    = &quot;&quot;;<br />
$requestedUrl    = $canonicalScheme .$canonicalServer .$requestUri;<br />
$canonicalUrl    = &quot;&quot;;<br />
$url             = parse_url($requestedUrl);<br />
$requestPath     = $url[&quot;path&quot;];<br />
$includeScript   = &quot;&quot;;<br />
$queryString     = $url[&quot;query&quot;];<br />
&nbsp;<br />
// keep misspelled URIs with nice search engine rankings<br />
if (&quot;$requestPath&quot; == &quot;/Sample.asp&quot;) {  // change this<br />
   $includeScript = $documentRoot .&quot;/sample.asp&quot;;  // change this<br />
}<br />
// &#8230;<br />
if (!empty($includeScript)) {<br />
   @header(&quot;HTTP/1.1 200 OK&quot;, TRUE, 200);<br />
   @include($includeScript);<br />
   exit;<br />
}<br />
&nbsp;<br />
// if the lowercase version exists, redirect to it<br />
$lcPath = strtolower($url[&quot;path&quot;]);<br />
$lcFile = $documentRoot .$lcPath;<br />
if (file_exists($lcFile) &#038;&#038; !stristr($requestUri,$thisFileName)) {<br />
    $canonicalUrl = $canonicalScheme .$canonicalServer .$lcPath;<br />
    if ($queryString) {<br />
        $canonicalUrl .= &quot;?&quot; .$queryString;<br />
    }<br />
    if ($url[&quot;fragment&quot;]) {<br />
        $canonicalUrl .= &quot;#&quot; .$url[&quot;fragment&quot;];<br />
    }<br />
}<br />
if (!empty($canonicalUrl)) {<br />
    @header(&quot;HTTP/1.1 301 Moved Permanently&quot;, TRUE, 301);<br />
    @header(&quot;Location: $canonicalUrl&quot;);<br />
    exit;<br />
}<br />
&nbsp;<br />
// serve the 404 error page<br />
@header(&quot;HTTP/1.1 404 Not found&quot;, TRUE, 404);<br />
@include($documentRoot .$errorPageUri);<br />
exit;<br />
?&gt;   </b></code><br />
(Edit the values in all lines marked with &#8220;// change this&#8221;.)</p>
<p>This script doesn&#8217;t handle case issues with query string variables and values. Query string canonicalization must be developed for each individual site. Also, capturing misspelled URLs with nice search engine rankings should be implemented utilizing a database table when you&#8217;ve more than a dozen or so. </p>
<p>Lets see what the /404handler.php script does with requests of non-existing files. </p>
<p>First we test the requested URI for invalid URLs which are nicely ranked at search engines. We don&#8217;t care much about duplicate content issues when the engines deliver targeted traffic. Here is an example (which admittedly doesn&#8217;t rank for anything but illustrates the functionality): both <a href="http://link-condom.com/sample.asp">/sample.asp</a> as well as <a href="http://link-condom.com/Sample.asp">/Sample.asp</a> deliver the same content, although there&#8217;s no /Sample.asp script. Of course a better procedure would be renaming /sample.asp to /Sample.asp, permanently redirecting /sample.asp to /Sample.asp in .htaccess, and changing all internal links accordinly.</p>
<p>Next we lookup the all lowercase version of the requested path. If such a file exists, we perform a permanent redirect to it. Example: <a href="http://link-condom.com/About.asp">/About.asp</a> 301-redirects to <a href="http://link-condom.com/about.asp">/about.asp</a>, which is the file that exists.</p>
<p>Finally, if everything we tried to find a suitable URI for the actual request failed, we send the client a 404 error code and output the error page. Example: <a href="http://link-condom.com/gimme404.asp" rel="nofollow crap">/gimme404.asp</a> doesn&#8217;t exist, hence /404handler.php responds with a 404-Not Found header and displays /error.asp, but <a href="http://link-condom.com/error.asp">/error.asp</a> directly requested responds with a 200-OK.</p>
<p>You can easily refine the script with other algorithms and mappings to adapt its somewhat primitive functionality to your project&#8217;s needs. </p>
<h3>Tweaking code for future maintenance</h3>
<p>Legacy code comes with repetition, redundancy and duplication caused by developers who love copy+paste respectively copy+paste+modify, or Web design software that generates static files from templates. Even when you&#8217;re not willing to do a complete revamp by shoving your contents into a CMS, you must replace the ASP code anyway, what gives you the opportunity to encapsulate all templated page areas. </p>
<p>Say your design tool created a bunch of .asp files which all contain the same sidebars, headers and footers. When you move those files to your new server, create PHP include files from each templated page area, then replace the duplicated HTML code with <code>&lt;?php @include("header.php"); ?&gt;</code>, <code>&lt;?php @include("sidebar.php"); ?&gt;</code>, <code>&lt;?php @include("footer.php"); ?&gt;</code> and so on. Note that when you&#8217;ve HTML code in a PHP include file, you must add <code>&lt;?php ?&gt;</code> before the first line of HTML code or contents in included files. Also, leading spaces, empty lines and such which don&#8217;t hurt in HTML, can result in errors with PHP statements like header(), because those fail when the server has sent anything to the user agent (even a single space, new line or tab is too much).</p>
<p>It&#8217;s a good idea to use PHP scripts that are included at the very top and bottom of all scripts, even when you currently have no idea what to put into those. Trust me and create top.php and bottom.php, then add the calls (<code>&lt;?php @include("top.php"); ?&gt;</code> [&#8230;] <code>&lt;?php @include("bottom.php"); ?&gt;</code>) to all scripts. Tomorrow you&#8217;ll write a generic routine that you must have in all scripts, and you&#8217;ll happily do that in top.php. The day after tomorrow you&#8217;ll paste the GoogleAnalytics tracking code into bottom.php. With complex sites you need more hooks. </p>
<h3>Using absolute URLs on different systems</h3>
<p>Another weak point is the use of relative URIs in links, image sources or references to feeds or external scripts. The lame excuse of most developers is that they need to test the site on their local machine, and that doesn&#8217;t work with absolute URLs. Crap. Of course it works. The first statement in top.php is <code><b><br />
@require($_SERVER[&quot;SERVER_NAME&quot;] .&quot;.php&quot;); </b></code><br />
This way you can set the base URL for each environment and your code runs everywhere. For development purposes on a subdomain you&#8217;ve a &#8220;dev.example.com.php&#8221; include file, on the production system example.com the file name resolves to &#8220;www.example.com.php&#8221;: <code><b><br />
&lt;?php<br />
$baseUrl = &#8220;http://example.com&#8221;;<br />
?&gt;  </b></code><br />
Then the menu in sidebar.php looks like: <code><b><br />
&lt;?php<br />
$classVMenu = &quot;vmenu&quot;;<br />
print &quot;<br />
&lt;img src=\&quot;$baseUrl/vmenuheader.png\&quot; width=\&quot;128\&quot; height=\&quot;16\&quot; alt=\&quot;MENU\&quot; /&gt;<br />
&lt;ul&gt;<br />
&lt;li&gt;&lt;a class=\&quot;$classVMenu\&quot; href=\&quot;$baseUrl/\&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;<br />
&lt;li&gt;&lt;a class=\&quot;$classVMenu\&quot; href=\&quot;$baseUrl/contact.asp\&quot;&gt;Contact&lt;/a&gt;&lt;/li&gt;<br />
&lt;li&gt;&lt;a class=\&quot;$classVMenu\&quot; href=\&quot;$baseUrl/sitemap.asp\&quot;&gt;Sitemap&lt;/a&gt;&lt;/li&gt;<br />
&#8230;<br />
&lt;/ul&gt;<br />
&quot;;<br />
?&gt; </b></code><br />
Mixing X/HTML with server sided scripting languages is fault-prone and makes maintenance a nightmare. Don&#8217;t make the same mistake as WordPress. Avoid crap like that: <code><br />
&lt;li&gt;&lt;a class=&quot;&lt;?php print $classVMenu; ?&gt;&quot; href=&quot;&lt;?php print $baseUrl; ?&gt;/contact.asp&quot;&gt;&lt;/a&gt;&lt;/li&gt; </code></p>
<h3>Error handling</h3>
<p>I refuse to discuss IIS error handling. On Apache servers you simply put ErrorDocument directives in your root&#8217;s .htaccess file: <code><b><br />
ErrorDocument 401 /get-the-fuck-outta-here.asp<br />
ErrorDocument 403 /get-the-fudge-outta-here.asp<br />
ErrorDocument 404 /404handler.php<br />
ErrorDocument 410 /410-gone-forever.asp<br />
ErrorDocument 503 /410-down-for-maintenance.asp<br />
# &#8230;<br />
Options -Indexes </b></code><br />
Then create neat pages for each HTTP response code which explain the error to the visitor and offer alternatives. Of course you can handle all response codes with one single script: <code></b><br />
ErrorDocument 401 /error.php?errno=401<br />
ErrorDocument 403 /error.php?errno=403<br />
ErrorDocument 404 /404handler.php<br />
ErrorDocument 410 /error.php?errno=410<br />
ErrorDocument 503 /error.php?errno=503<br />
# &#8230;<br />
Options -Indexes </b></code><br />
Note that relative URLs in pages or scripts called by ErrorDocument directives don&#8217;t work. <b>Don&#8217;t use absolute URLs in ErrorDocument directives itself, because this way you get 302 response codes for 404 errors and crap like that.</b> If you cover the 401 response code with a fully qualified URL, your server will explode. (Ok, it will just hang but that&#8217;s bad enough.) For more information please read my pamphlet <a href="http://sebastians-pamphlets.com/why-proper-error-handling-is-important/">Why error handling is important</a>. </p>
<p>Last but not least create a robots.txt file in the root. If you&#8217;ve nothing to hide from search engine crawlers, this one will suffice: <code></b><br />
User-agent: *<br />
Disallow:<br />
Allow: /<br />
</b></code></p>
<p>I&#8217;m aware that this tiny guide can&#8217;t cover everything. It should give you an idea of the pitfalls and possible solutions. If you&#8217;re somewhat code-savvy my code snippets will get you started, but hire an expert when you plan to migrate a large site. And don&#8217;t view the source code of <a href="http://link-condom.com/">link-condom.com</a> pages where I didn&#8217;t implement all tips from this tutorial. <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/how-to-migrate-a-website-from-iis-asp-to-apache-php/", "style": "big", "title": "Upgrading from IIS/ASP to Apache/PHP" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/how-to-migrate-a-website-from-iis-asp-to-apache-php/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Act out your sophisticated affiliate link paranoia</title>
		<link>http://sebastians-pamphlets.com/linking-guide-for-paranoid-affiliate-marketers/</link>
		<comments>http://sebastians-pamphlets.com/linking-guide-for-paranoid-affiliate-marketers/#comments</comments>
		<pubDate>Tue, 13 Nov 2007 07:09:30 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Search Quality]]></category>

		<category><![CDATA[Risky Linkage]]></category>

		<category><![CDATA[Web development]]></category>

		<category><![CDATA[X-Robots-Tag]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[Paid Links]]></category>

		<category><![CDATA[Crawler Directives]]></category>

		<category><![CDATA[SEO]]></category>

		<category><![CDATA[Google]]></category>

		<category><![CDATA[robots.txt]]></category>

		<category><![CDATA[E-Commerce]]></category>

		<category><![CDATA[Cloaking]]></category>

		<category><![CDATA[Nofollow]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/linking-guide-for-paranoid-affiliate-marketers/</guid>
		<description><![CDATA[
My recent posts on managing affiliate links and nofollow cloaking paid links led to so many reactions from my readers that I thought explaining possible protection levels could make sense. Google&#8217;s request to condomize affiliate links is a bit, well, thin when it comes to technical tips and tricks:
Links purchased for advertising should be designated [...]]]></description>
			<content:encoded><![CDATA[
<p><img src="http://sebastians-pamphlets.com/img/posts/paranoid-affiliate-link.png" width="250" height="231" border="0" align="right" style="margin-left:4px;" alt="GOOD: paranoid affiliate link" title="Paranoid on affiliate links" />My recent posts on <a href="http://sebastians-pamphlets.com/google-recommends-screwing-affiliates-in-exchange-for-better-serp-positioning/">managing affiliate links</a> and <a href="http://sebastians-pamphlets.com/a-pragmatic-defense-against-googles-anti-paid-links-campaign/">nofollow cloaking</a> <a href="http://sebastians-pamphlets.com/text-link-broker-woes-smart-paid-links-sniffers-fromgoogle/">paid links</a> led to so many reactions from my readers that I thought explaining possible protection levels could make sense. <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=66736">Google&#8217;s request to condomize affiliate links</a> is a bit, well, thin when it comes to technical tips and tricks:<br />
<blockquote>Links purchased for advertising should be designated as such. This can be done in several ways, such as:<br />
    * Adding a rel=&#8221;nofollow&#8221; attribute to the &lt;a&gt; tag<br />
    * Redirecting the links to an intermediate page that is blocked from search engines with a robots.txt file</p></blockquote>
<p> Also, Google doesn&#8217;t define <a href="http://sebastians-pamphlets.com/links/categories/?cat=paid-links">paid links</a> that clearly, so try this <a href="http://www.stonetemple.com/blog/?p=196">paid link definition</a> instead before your read on. <b>Here is my linking guide for the paranoid affiliate marketer.</b></p>
<p><a href="http://www.google.com/support/webmasters/bin/answer.py?answer=76465">Google recommends hiding of any content provided by affiliate programs from their crawlers</a>. That means not only links and banner ads, so think about tactics to hide content pulled from a merchants data feed too. Linked graphics along with text links, testimonials and whatnot copied from an affiliate program&#8217;s sales tools page count as duplicate content (snippet) in its worst occurance.</p>
<p>Pasting code copied from a merchant&#8217;s site into a page&#8217;s or template&#8217;s HTML is not exactly a smart way to put ads. Those ads aren&#8217;t manageable nor trackable, and when anything must be changed, editing tons of files is a royal PITA. Even when you&#8217;re just running a few ads on your blog, a simple ad management script allows flexible administration of your adverts. </p>
<p>There are tons of such scripts out there, so I don&#8217;t post a complete solution, but just the code which saves your ass when a search engine hating your ads and paid links comes by. To keep it simple and stupid my code snippets are mostly taken from this blog, so when you&#8217;ve a WordPress blog you can adapt them with ease. </p>
<h3>Cover your ass with a linking policy</h3>
<p>Googlers as well as hired guns do review Web sites for violations of Google&#8217;s guidelines, also competitors might be in the mood to turn you in with a spam report or paid links report. A (prominently linked) <a href="http://sebastians-pamphlets.com/links/full-disclosure/">full disclosure of your linking attitude</a> can help to pass a human review by search engine staff. By the way, having a <a href="http://sebastians-pamphlets.com/about/policies/#commenting">policy for dofollowed blog comments</a> is also a good idea.</p>
<p>Since crawler directives like <a href="http://sebastians-pamphlets.com/links/categories/?cat=nofollow">link condoms</a> are for search engines (only), and those pay attention to your source code and hints addressing search engines like <a href="http://sebastians-pamphlets.com/links/categories/?cat=robotstxt">robots.txt</a>, you should leave a note <a href="http://sebastians-pamphlets.com/robots.txt" rel="nofollow nocontent">there</a> too, look into the source of this page for an example. <a onclick="showContent('sample-code-disclosure'); this.style.display = 'none'; return false;">View sample HTML comment.</a> <b id="sample-code-disclosure" style="display:none;">Sample HTML comment: <code>&lt;&#33;--</code>This site serves machine-readable disclosures, e.g. crawler directives like rel-nofollow applied to links with commercial intent, to Web robots only.<code>--&gt;</code></b> </p>
<h3>Block crawlers from your propaganda scripts</h3>
<p>Put all your stuff related to advertising (scripts, images, movies&#8230;) in a subdirectory and disallow search engine crawling in your <a href="http://www.smart-it-consulting.com/article.htm?node=140&#038;page=46">/robots.txt</a> file: <code><br />
User-agent: *<br />
Disallow: /propaganda/ </code><br />
Of course you&#8217;ll use an innocuous name like &#8220;gnisitrevda&#8221; for this folder, which lacks a default document and can&#8217;t get browsed because you&#8217;ve a <code><br />
Options -Indexes </code><br />
statement in your .htaccess file. (Watch out, Google knows what &#8220;gnisitrevda&#8221; means, so be creative or cryptic.)</p>
<p>Crawlers sent out by major search engines do respect robots.txt, hence it&#8217;s guaranteed that regular spiders don&#8217;t fetch it. As long as you don&#8217;t cheat too much, you&#8217;re not haunted by those legendary anti-webspam bots sneakily accessing your site via AOL proxies or Level3 IPs. A robots.txt block doesn&#8217;t prevent you from surfing search engine staff, but I don&#8217;t tell you things you&#8217;d better hide from Matt&#8217;s gang.</p>
<h3>Detect search engine crawlers</h3>
<p>Basically there are three common methods to detect requests by search engine crawlers.
<ol>
<li>Testing the user agent name (HTTP_USER_AGENT) for strings like &#8220;Googlebot&#8221;, &#8220;Slurp&#8221;, &#8220;MSNbot&#8221; or so which identify crawlers. That&#8217;s easy to spoof, for example <a href="http://sebastians-pamphlets.com/referrer-spoofing-with-prefbar-341/">PrefBar for FireFox</a> lets you choose from a list of user agents.</li>
<li>Checking the user agent name, and only when it indicates a crawler, verifying the requestor&#8217;s IP address with a reverse lookup, respectively against a cache of verified crawler IP addresses and host names.</li>
<li>Maintaining a list of all search engine crawler IP addresses known to man,  checking the requestor&#8217;s IP (REMOTE_ADDR) against this list. (That alone isn&#8217;t bullet-proof, but I&#8217;m not going to write a tutorial on industrial-strength <strike>cloaking</strike> IP delivery, I leave that to the real <a href="http://fantomaster.com/fantomNews">experts</a>.)</li>
</ol>
<p>For our purposes we use method 1) and 2). When it comes to outputting ads or other paid links, checking the user agent is save enough. Also, this allows your business partners to evaluate your linkage using a crawler as user agent name. Some affiliate programs won&#8217;t activate your account without testing your links. When crawlers try to follow affiliate links on the other hand, you need to verify their IP addresses for two reasons. First, you should be able to upsell spoofing users too. Second, if you allow crawlers to follow your affiliate links, this may have impact on the merchants&#8217; search engine rankings, and that&#8217;s evil in Google&#8217;s eyes.  </p>
<p>We use two PHP functions to detect search engine crawlers. checkCrawlerUA() returns TRUE and sets an expected crawler host name, if the user agent name identifies a major search engine&#8217;s spider, or FALSE otherwise. checkCrawlerIP($string) verifies the requestor&#8217;s IP address and returns TRUE if the user agent is indeed a crawler, or FALSE otherwise. checkCrawlerIP() does a primitive caching in a flat file, so that once a crawler was verified on its very first content request, it can be detected from this cache to avoid pretty slow DNS lookups. The input parameter is any string which will make it into the log file. checkCrawlerIP() does not verify an IP address if the user agent string doesn&#8217;t match a crawler name. </p>
<p><b id="grab-php-code-check-crawler"><a onclick="showContent('php-code-check-crawler'); return false;">View</a>|<a onclick="hideContent('php-code-check-crawler'); return false;">hide</a> PHP code.</b> (If you&#8217;ve disabled JavaScript you can&#8217;t grab the PHP source code!)<br />
<code id="php-code-check-crawler" style="display:none;"><b><br />
// file system path to crawler IP log, scripts etc.,<br />
// without trailing slash:<br />
$includePath   = $_SERVER[&quot;DOCUMENT_ROOT&quot;] . &quot;/propaganda&quot;;<br />
// edit &quot;propaganda&quot; and CHMOD 777 the directory !<br />
// file names:<br />
$crawlerIps  = $includePath .&quot;/crawler-ip-addresses.txt&quot;;<br />
// misc. stuff:<br />
$timestamp     = date(&#8217;Y-m-d H:i:s&#8217;);<br />
$ipAddy        = $_SERVER[&quot;REMOTE_ADDR&quot;];<br />
$referrer      = $_SERVER[&quot;HTTP_REFERER&quot;];<br />
$userAgent     = $_SERVER[&quot;HTTP_USER_AGENT&quot;];<br />
$requestUri    = $_SERVER[&quot;REQUEST_URI&quot;];<br />
$queryString   = $_SERVER[&quot;QUERY_STRING&quot;];<br />
$isCrawler     = FALSE;<br />
$crawlerServer = &quot;&quot;;<br />
$delimiter     = &quot;|&quot;;<br />
$idString      = &quot;&quot;;<br />
if (empty($includePath)) {<br />
   $includePath = $_SERVER[&quot;DOCUMENT_ROOT&quot;] . &quot;/propaganda&quot;; // CHMOD 777<br />
}<br />
// Write a file to disk<br />
if (!function_exists(&quot;writeLocalFile&quot;)) {<br />
function writeLocalFile ($file, $content) {<br />
   if (!is_writable($file)) {<br />
      $lok = @chmod ( $file, 0777 );<br />
   }<br />
   // file_put_contents() not avail in PHP 4.3x<br />
   $fp = @fopen(&quot;$file&quot;,&quot;w+&quot;);<br />
   if ($fp) {<br />
       $lOk = @fwrite($fp, $content, strlen($content));<br />
       @fclose($fp);<br />
       // make sure file may get overwritten or removed later on<br />
       $lok = @chmod ( $file, 0777 );<br />
       return TRUE;<br />
   } // endif $fp<br />
   return FALSE;<br />
} // end function writeLocalFile<br />
}<br />
if (!function_exists(&quot;checkCrawlerUA&quot;)) {<br />
function checkCrawlerUA () {<br />
    GLOBAL $userAgent;<br />
    GLOBAL $crawlerServer;<br />
    $crawlerServer = &quot;&quot;;<br />
    $crawlers  = array(&quot;Googlebot&quot;,&quot;Mediapartners&quot;,&quot;Slurp&quot;,&quot;MSNbot&quot;,&quot;Ask&quot;,&quot;Teoma&quot;);<br />
    foreach ($crawlers as $crawler) {<br />
        if (stristr($userAgent,$crawler)) {<br />
            if (stristr($crawler,&quot;Googlebot&quot;) ||<br />
                stristr($crawler,&quot;Mediapartners&quot;)) {<br />
                $crawlerServer = &quot;.googlebot.com&quot;;<br />
            } // Google<br />
            if (stristr($crawler,&quot;Slurp&quot;)) {<br />
                $crawlerServer = &quot;.crawl.yahoo.net&quot;;<br />
            } // Yahoo<br />
            if (stristr($crawler,&quot;MSNbot&quot;)) {<br />
                $crawlerServer = &quot;.search.live.com&quot;;<br />
            } // MSN/Live<br />
            if (stristr($crawler,&quot;Ask&quot;) ||<br />
                stristr($crawler,&quot;Teoma&quot;)) {<br />
                $crawlerServer = &quot;.ask.com&quot;;<br />
            } // Ask<br />
        }<br />
    } // foreach crawlers<br />
    if (!empty($crawlerServer)) return TRUE;<br />
    return FALSE;<br />
} // end function checkCrawlerUA<br />
}<br />
if (!function_exists(&quot;checkCrawlerIP&quot;)) {<br />
function checkCrawlerIP ($idString) {<br />
    GLOBAL $ipAddy;<br />
    GLOBAL $crawlerIps;<br />
    GLOBAL $delimiter;<br />
    GLOBAL $timestamp;<br />
    GLOBAL $userAgent;<br />
    GLOBAL $crawlerServer;<br />
    $isCrawler = checkCrawlerUA();<br />
    if ($isCrawler === FALSE)  return FALSE;<br />
    if (empty($crawlerServer)) return FALSE;<br />
//<br />
// DEBUG: $crawlerServer = &quot;.national-net.com&quot;;<br />
// Use your ISPs host name for testing with a spoofed user agent name<br />
//<br />
    $crawlerIpsContent = @file_get_contents($crawlerIps);<br />
    if (!empty($crawlerIpsContent)) {<br />
        if (stristr($crawlerIpsContent, &quot;\n$ipAddy$delimiter&quot;)) {<br />
            return TRUE;<br />
        }<br />
    }<br />
    $crawlerHost = @gethostbyaddr($ipAddy);<br />
    if (!stristr($crawlerHost,$crawlerServer)) {<br />
        return FALSE;<br />
    }<br />
    if (&quot;$crawlerHost&quot; == &quot;$ipAddy&quot;) {<br />
        return FALSE;<br />
    }<br />
    $ipAddyRev = @gethostbyname($crawlerHost);<br />
    if (&quot;$ipAddyRev&quot; != &quot;$ipAddy&quot;) {<br />
        return FALSE;<br />
    }<br />
    $crawlerIpsContent .= &quot;\n&quot; .$ipAddy .$delimiter<br />
                          .$timestamp   .$delimiter<br />
                          .$crawlerHost .$delimiter<br />
                          .$idString    .$delimiter<br />
                          .$userAgent   .$delimiter;<br />
    $lOk = writeLocalFile ($crawlerIps, $crawlerIpsContent);<br />
    return TRUE;<br />
} // end function checkCrawlerIP<br />
}<br />
</b></code><br />
Grab and implement the PHP source, then you can code statements like <code><br />
$isSpider = checkCrawlerUA ();<br />
...<br />
if ($isSpider) {<br />
    $relAttribute = &quot; rel=\&quot;nofollow\&quot; &quot;;<br />
}<br />
...<br />
$affLink = &quot;&lt;a href=\&quot;$affUrl\&quot; $relAttribute&gt;call for action&lt;/a&gt;&quot;;<br />
</code><br />
or <code><br />
$isSpider = checkCrawlerIP ($sponsorUrl);<br />
...<br />
if ($isSpider) {<br />
    // don't redirect to the sponsor, return a 403 or 410 instead<br />
}</code><br />
More on that later.</p>
<h3>Don&#8217;t deliver your advertising to search engine crawlers</h3>
<p>It&#8217;s possible to serve totally clean pages to crawlers, that is without any advertising, not even JavaScript ads like AdSense&#8217;s script calls. Whether you go that far or not depends on the grade of your paranoia. Suppressing ads on a (thin|sheer) affiliate site can make sense. Bear in mind that hiding all promotional links and related content can&#8217;t guarantee indexing, because Google doesn&#8217;t index shitloads of templated pages witch hide duplicate content as well as ads from crawling, without carrying a single piece of somewhat compelling content.</p>
<p>Here is how you could output a totally uncrawlable banner ad: <code><br />
...<br />
$isSpider = checkCrawlerIP ($PHP_SELF);<br />
...<br />
print &quot;&lt;div class=\&quot;css-class-sidebar robots-nocontent\&quot;&gt;&quot;;<br />
// output RSS buttons or so<br />
if (!$isSpider) {<br />
    print &quot;&lt;script type=\&quot;text/javascript\&quot; src=\&quot;http://sebastians-pamphlets.com/propaganda/output.js.php? adName=seobook&#038;adServed=banner\&quot;&gt;&lt;/script&gt;&quot;;<br />
    ...<br />
}<br />
...<br />
print &quot;&lt;/div&gt;\n&quot;;<br />
...</code><br />
Lets look at the code above. First we detect crawlers &#8220;without doubt&#8221; (well, in some rare cases it can still happen that a suspected Yahoo crawler comes from a non-&#8217;.crawl.yahoo.net&#8217; host but another IP owned by Yahoo, Inktomi, Altavista or AllTheWeb/FAST, and I&#8217;ve seen similar reports of such misbehavior for other engines too, but that might have been employees surfing with a crawler-UA).</p>
<p>Currently the <em>robots-nocontent</em>&nbsp; class name in the DIV is not supported by Google, MSN and Ask, but it tells Yahoo that everything in this DIV shall not be used for ranking purposes. That doesn&#8217;t conflict with class names used with your CSS, because each X/HTML element can have an unlimited list of space delimited class names. Like Google&#8217;s section targeting that&#8217;s a <a href="http://sebastians-pamphlets.com/yahoo-search-going-to-torture-webmasters/">crappy crawler directive</a>, though. However, it doesn&#8217;t hurt to make use of this Yahoo feature with all sorts of screen real estate that is not relevant for search engine ranking algos, for example RSS links (use autodetect and pings to submit), &#8220;buy now&#8221;/&#8221;view basket&#8221; links or references to TOS pages and alike, templated text like terms of delivery (but not the street address provided for local search) &#8230; and of course ads.</p>
<p>Ads aren&#8217;t outputted when a crawler requests a page. Of course that&#8217;s cloaking, but unless the united search engine geeks come out with a standardized procedure to handle code and contents which aren&#8217;t relevant for indexing that&#8217;s not <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=66355">deceitful cloaking</a> in my opinion. Interestingly, in many cases cloaking is the last weapon in a webmaster&#8217;s arsenal that s/he can fire up to comply to search engine rules when everything else fails, because the crawlers behave more and more like browsers. </p>
<p>Delivering user specific contents in general is fine with the engines, for example geo targeting, profile/logout links, or buddy lists shown to registered users only and stuff like that, aren&#8217;t penalized. Since Web robots can&#8217;t pull out the plastic, there&#8217;s no reason to serve them ads just to waste bandwidth. In some cases search engines even require cloaking, for example to prevent their crawlers from fetching URLs with tracking variables and unavoidable duplicate content. (<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=35769">Example from Google</a>: &#8220;Allow search bots to crawl your sites without session IDs or arguments that track their path through the site&#8221; is a call for <a href="http://www.smart-it-consulting.com/article.htm?node=148&#038;page=103">search engine friendly URL cloaking</a>.) </p>
<h3>Is hiding ads from crawlers &#8220;safe with Google&#8221; or not?</h3>
<p><img src="http://sebastians-pamphlets.com/img/posts/uncloaked-affiliate-link.png" width="200" height="188" border="0" align="right" style="margin-left:4px;" alt="BAD: uncloaked affiliate link" title="Uncloaked affiliate link" />Cloaking ads away is a double edged sword from a search engine&#8217;s perspective. Way too strictly interpreted that&#8217;s against the cloaking rule which states &#8220;don&#8217;t show crawlers other content than humans&#8221;, and search engines like to be aware of advertising in order to rank estimated user experiences algorithmically. On the other hand they provide us with mechanisms (Google&#8217;s section targeting or Yahoo&#8217;s robots-nocontent class name) to disable such page areas for ranking purposes, and they code their own ads in a way that crawlers don&#8217;t count them as on-the-page contents.</p>
<p>Although Google says that AdSense text link ads are content too, they ignore their textual contents in ranking algos. Actually, their crawlers and indexers don&#8217;t render them, they just notice the number of script calls and their placement (at least if above the fold) to identify <acronym title="Made For AdSense/Advertising">MFA</acronym> pages. In general, they ignore ads as well as other content outputted with client sided scripts or hybrid technologies like AJAX, at least when it comes to rankings. </p>
<p>Since in theory the contents of JavaScript ads aren&#8217;t considered food for rankings, cloaking them completely away (supressing the JS code when a crawler fetches the page) can&#8217;t be wrong. Of course these script calls as well as on-page JS code are a ranking factors. Google possibly counts ads, maybe calculates even ratios like screen size used for advertising etc. vs. space used for content presentation to determine whether a particular page provides a good surfing experience for their users or not, but they can&#8217;t argue seriously that hiding such tiny signals &#8211;which they use for the sole purposes of possible downranks&#8211; is against their guidelines.</p>
<p>For ages search engines reps used to encourage webmasters to obfuscate all sorts of stuff they want to hide from crawlers, like commercial links or redundant snippets, by linking/outputting with JavaScript instead of crawlable X/HTML code. Just because their crawlers evolve, that doesn&#8217;t mean that they can take back this advice. All this JS stuff is out there, on gazillions of sites, often on pages which will never be edited again.</p>
<p><b>Dear search engines, if it does not count, then you cannot demand to keep it crawlable.</b> Well, a few super mega white hat <acronym title="Dougie ...">trolls</acronym> might disagree, and depending on the implementation on individual sites maybe hiding ads isn&#8217;t totally riskless in any case, so decide yourself. I just cloak machine-readable disclosures because crawler directives are not for humans, but don&#8217;t try to hide the fact that I run ads on this blog.</p>
<p>Usually I don&#8217;t argue with fair vs. unfair, because we talk about <strike>war</strike> business here, what means that everything goes. However, Google does everything to talk the whole Internet into <strike>obfuscating</strike> disclosing ads with link condoms of any kind, and they take a lot of flak for such campaigns, hence I doubt they would cry foul today when webmasters hide both client sided as well as server sided delivery of advertising from their crawlers. Penalizing for delivery of sheer contents would be unfair. <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> (Of course that&#8217;s stuff for a great debate. If Google decides that hiding ads from spiders is evil, they will react and don&#8217;t care about bad press. So please don&#8217;t take my opinion as professional advice. I might change my mind tomorrow, because actually I can imagine why Google might raise their eyebrows over such statements.)</p>
<h3>Outputting ads with JavaScript, preferably in iFrames</h3>
<p>Delivering adverts with JavaScript does not mean that one can&#8217;t use server sided scripting to adjust them dynamically. With content management systems it&#8217;s not always possible to use PHP or so. In WordPress for example, PHP is executable in templates, posts and pages (requires a plugin), but not in sidebar widgets. A piece of JavaScript on the other hand works (nearly) everywhere, as long as it doesn&#8217;t come with single quotes (WordPress escapes them for storage in its MySQL database, and then fails to output them properly, that is single quotes are converted to fancy symbols which break eval&#8217;ing the PHP code).</p>
<p>Lets see how that works. Here is a banner ad created with a PHP script and delivered via JavaScript:<br />
<script type="text/javascript" src="http://sebastians-pamphlets.com/ads/output.js.php?adName=seobook&#038;adServed=banner"></script><br />
And here is the JS call of the PHP script: <code><br />
&lt;script type=&quot;text/javascript&quot; src=&quot;http://sebastians-pamphlets.com/propaganda/output.js.php? adName=seobook&#038;adServed=banner&quot;&gt;&lt;/script&gt;</code></p>
<p>The PHP script <code>/propaganda/output.js.php</code> evaluates the query string to pull the requested ad&#8217;s components. In case it&#8217;s expired (e.g. promotions of conferences, affiliate program went belly up or so) it looks for an alternative (there are tons of neat ways to deliver different ads dependent on the requestor&#8217;s location and whatnot, but that&#8217;s not the point here, hence the lack of more examples). Then it checks whether the requestor is a crawler. If the user agent indicates a spider, it adds rel=nofollow to the ad&#8217;s links. Once the HTML code is ready, it outputs a JavaScript statement: <code><br />
document.write(&lsquo;&lt;a href=&quot;http://sebastians-pamphlets.com/propaganda/router.php? adName=seobook&#038;adServed=banner&quot; title=&quot;DOWNLOAD THE BOOK ON SEO!&quot;&gt;&lt;img src=&quot;http://sebastians-pamphlets.com/propaganda/seobook/468-60.gif&quot; width=&quot;468&quot; height=&quot;60&quot; border=&quot;0&quot; alt=&quot;The only current book on SEO&quot; title=&quot;The only current book on SEO&quot;  /&gt;&lt;/a&gt;&rsquo;); </code> which the browser executes within the <code>script</code> tags (replace single quotes in the HTML code with double quotes). A static ad for surfers using ancient browsers goes into the noscript tag. </p>
<p>Matt Cutts <a href="http://www.stonetemple.com/articles/interview-matt-cutts.shtml">said</a> that <a href="http://www.mattcutts.com/blog/bot-obedience-herding-googlebot/#comment-45561">JavaScript links don&#8217;t prevent Googlebot from crawling</a>, but that <a href="http://www.seomoz.org/blog/the-paid-links-debate-rages-on-ses-san-jose-2007">those links</a> <a href="http://www.mattcutts.com/blog/how-to-report-paid-links/#comment-101482">don&#8217;t count for rankings</a> (not long ago I read a more recent quote from Matt where he stated that this is future-proof, but I can&#8217;t find the link right now). We know that Google can interpret internal and external JavaScript code, as long as it&#8217;s fetchable by crawlers, so I wouldn&#8217;t say that delivering advertising with client sided technologies like JavaScript or Flash is a bullet-proof procedure to hide ads from Google, and the same goes for other major engines. That&#8217;s why I use rel-nofollow &#8211;on crawler requests&#8211; even in JS ads.</p>
<p>Change your user agent name to Googlebot or so, install <a href="http://www.mattcutts.com/blog/seeing-nofollow-links/">Matt&#8217;s show nofollow hack</a> or something similar, and you&#8217;ll see that the affiliate-URL gets nofollow&#8217;ed for crawlers. The dotted border in firebrick is extremely ugly, detecting condomized links this way is pretty popular, and I want to serve nice looking pages, thus I really can&#8217;t offend my readers with nofollow&#8217;ed links (although I don&#8217;t care about crawler spoofing, actually that&#8217;s a good procedure to let advertisers check out my linking attitude).</p>
<p>We look at the affiliate URL from the code above later on, first lets discuss other ways to make ads more search engine friendly. Search engines don&#8217;t count pages displayed in iFrames as on-page contents, especially not when the iFrame&#8217;s content is hosted on another domain. Here is an example straight from the horse&#8217;s mouth: <code><br />
&lt;iframe name=&quot;google_ads_frame&quot; src=&quot;http://pagead2.googlesyndication.com/pagead/ads? very-long-and-ugly-query-string&quot; marginwidth=&quot;0&quot; marginheight=&quot;0&quot; vspace=&quot;0&quot; hspace=&quot;0&quot; allowtransparency=&quot;true&quot; frameborder=&quot;0&quot; height=&quot;90&quot; scrolling=&quot;no&quot; width=&quot;728&quot;&gt;&lt;/iframe&gt;</code> In a noframes tag we could put a static ad for surfers using browsers which don&#8217;t support frames/iFrames. </p>
<p>If for some reasons you don&#8217;t want to detect crawlers, or it makes sound sense to hide ads from other Web robots too, you could encode your JavaScript ads. This way you deliver totally and utterly useless gibberish to anybody, and just browsers requesting a page will render the ads. Example: any sort of text or html block that you would like to encrypt and hide from snoops, scrapers, parasites, or bots, can be run through Michael&#8217;s <a href="http://www.bad-neighborhood.com/htmlhashing.htm">Full Text/HTML Obfuscator Tool</a> (hat tip to <a href="http://www.seo-scoop.com/2007/09/13/new-tool-to-hide-stuff/">Donna</a>).</p>
<h3>Always redirect to affiliate URLs</h3>
<p>There&#8217;s absolutely no point in using ugly affiliate URLs on your pages. Actually, that&#8217;s the last thing you want to do for various reasons.
<ul>
<li>For example, affiliate URLs as well as source codes can change, and you don&#8217;t want to edit tons of pages if that happens.</li>
<li>When an affiliate program doesn&#8217;t work for you, goes belly up or bans you, you need to route all clicks to another destination when the shit hits the fan. In an ideal world, you&#8217;d replace outdated ads completely with one mouse click or so.</li>
<li>Tracking ad clicks is no fun when you need to pull your stats from various sites, all of them in another time zone, using their own &#8211;often confusing&#8211; layouts, providing different views on your data, and delivering program specific interpretations of impressions or click throughs. Also, if you don&#8217;t track your outgoing traffic, some sponsors will cheat and you can&#8217;t prove your gut feelings.</li>
<li>Scrapers can steal revenue by replacing affiliate codes in URLs, but may overlook hard coded absolute URLs which don&#8217;t smell like affiliate URLs.</li>
<li><b>&#8230;</b></li>
</ul>
<p>When you replace all affiliate URLs with the URL of a smart redirect script on one of your domains, you can really <b>manage your affiliate links</b>. There are many more good reasons for utilizing ad-servers, for example smart search engines which might think that your advertising is overwhelming.</p>
<p>Affiliate links provide great footprints. Unique URL parts respectively <b>query string variable names</b> gathered by Google from all affiliate programs out there are one clear signal they use to identify affiliate links. The <b>values</b> identify the single affiliate marketer. Google loves to identify networks of ((thin) affiliate) sites by affiliate IDs. That does not mean that Google detects each and every affiliate link at the time of the very first fetch by Ms. Googlebot and the possibly following indexing. Processes identifying pages with (many) affiliate links and sites plastered with ads instead of unique contents can run afterwords, utilizing a well indexed database of links and linking patterns, reporting the findings to the search index respectively delivering minus points to the query engine. Also, that doesn&#8217;t mean that affiliate URLs are the one and only trackable footmark Google relies on. But that&#8217;s one trackable footprint you can avoid to some degree. </p>
<p>If the redirect-script&#8217;s location is on the same server (in fact it&#8217;s not thanks to symlinks) and not named &#8220;adserver&#8221; or so, chances are that a heuristic check won&#8217;t identify the link&#8217;s intent as promotional. Of course statistical methods can discover your affiliate links by analyzing patterns, but those might be similar to patterns which have nothing to do with advertising, for example click tracking of editorial votes, links to contact pages which aren&#8217;t crawlable with paramaters, or similar &#8220;legit&#8221; stuff. However, you can&#8217;t fool smart algos forever, but if you&#8217;ve a good reason to hide ads every little might help. Of course, providing lots of great contents countervails lots of ads (from a search engine&#8217;s point of view, and users might agree on this).</p>
<p>Besides all these (pseudo) black hat thoughts and reasoning, there is a way more important advantage of redirecting links to sponsors: blocking crawlers. Yup, search engine crawlers must not follow affiliate URLs, because it doesn&#8217;t benefit you (<a href="http://sebastians-pamphlets.com/google-recommends-screwing-affiliates-in-exchange-for-better-serp-positioning/">usually</a>). Actually, every affiliate link is a useless PageRank leak. Why should you boost the merchants search engine rankings? Better take care of your own rankings by hiding such outgoing links from crawlers, and stopping crawlers before they spot the redirect, if they by accident found an affiliate link without link condom.</p>
<h3>The behavior of an adserver URL masking an affiliate link</h3>
<p>Lets look at the redirect-script&#8217;s URL from my code example above:<br />
<a href="http://sebastians-pamphlets.com/ads/router.php?adName=seobook&#038;adServed=banner">/propaganda/router.php?adName=seobook&#038;adServed=banner</a><br />
On request of router.php the $adName variable identifies the affiliate link, $adServed tells which sort/type/variation of ad was clicked, and all that gets stored with a timestamp under title and URL of the page carrying the advert. </p>
<p>Now that we&#8217;ve covered the statistical requirements, router.php calls the checkCrawlerIP() function setting $isSpider to TRUE only when both the user agent as well as the host name of the requestor&#8217;s IP address identify a search engine crawler, and a reverse DNS lookup equals the requestor&#8217;s IP addy.</p>
<p>If the requestor is not a verified crawler, router.php does a 307 redirect to the sponsor&#8217;s landing page: <code><br />
$sponsorUrl      = &quot;http://www.seobook.com/262.html&quot;;<br />
$requestProtocol = $_SERVER[&quot;SERVER_PROTOCOL&quot;];<br />
$protocolArr     = explode(&quot;/&quot;,$requestProtocol);<br />
$protocolName    = trim($protocolArr[0]);<br />
$protocolVersion = trim($protocolArr[1]);<br />
if (stristr($protocolName,&quot;HTTP&quot;)<br />
    &#038;&#038; strtolower($protocolVersion) > &quot;1.0&quot; ) {<br />
    $httpStatusCode = 307;<br />
}<br />
else {<br />
    $httpStatusCode = 302;<br />
}<br />
$httpStatusLine = &quot;$requestProtocol $httpStatusCode Temporary Redirect&quot;;<br />
@header($httpStatusLine, TRUE, $httpStatusCode);<br />
@header(&quot;Location: $sponsorUrl&quot;);<br />
exit;</code><br />
A 307 redirect avoids caching issues, because 307 redirects must not be cached by the user agent. That means that changes of sponsor URLs take effect immediately, even when the user agent has cached the destination page from a previous redirect. If the request came in via HTTP/1.0, we must perform a 302 redirect, because the 307 response code was introduced with HTTP/1.1 and some older user agents might not be able to handle 307 redirects properly. User agents can cache the locations provided by 302 redirects, so possibly when they run into a page known to redirect, they might request the outdated location. For obvious reasons we can&#8217;t use the 301 response code, because 301 redirects are always cachable. (<a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/">More information on HTTP redirects</a>.)</p>
<p>If the requestor is a major search engine&#8217;s crawler, we perform the most brutal bounce back known to man: <code><br />
if ($isSpider) {<br />
    @header(&quot;HTTP/1.1 403 Sorry Crawlers Not Allowed&quot;, TRUE, 403);<br />
    @header(&quot;X-Robots-Tag: nofollow,noindex,noarchive&quot;);<br />
    exit;<br />
}</code><br />
The 403 response code translates to &#8220;kiss my ass and get the fuck outta here&#8221;. The X-Robots-Tag in the HTTP header instructs crawlers that the requested URL must not be indexed, doesn&#8217;t provide links the poor beast could follow, and must not be publically cached by search engines. In other words the HTTP header tells the search engine &#8220;forget this URL, don&#8217;t request it again&#8221;. Of course we could use the 410 response code instead, which tells the requestor that a resource is irrevocably dead, gone, vanished, non-existent, and further requests are forbidden. Both the 403-Forbidden response as well as the 410-Gone return code prevent you from URL-only listings on the SERPs (once the URL was crawled). Personally, I prefer the 403 response, because it perfectly and unmistakably expresses my opinion on this sort of search engine guidelines, although currently nobody except Google understands or supports X-Robots-Tags in HTTP headers.</p>
<p>If you don&#8217;t use URLs provided by affiliate programs, your affiliate links can never influence search engine rankings, hence the engines are happy because you did their job so obedient. Not that they otherwise would count (most of) your affiliate links for rankings, but forcing you to castrate your links yourself makes their life much easier, and you don&#8217;t need to live in fear of penalties.</p>
<h3 id="recap-hide-afflinks">Recap</h3>
<p><img src="http://sebastians-pamphlets.com/img/posts/prospering-affiliate-link.png" width="200" height="200" border="0" align="right" style="margin-left:4px;" alt="NICE: prospering affiliate link" title="Prospering affiliate link" />Before you output a page carrying ads, paid links, or other selfish links with commercial intent, check if the requestor is a search engine crawler, and act accordingly.</p>
<p>Don&#8217;t deliver different (editorial) contents to users and crawlers, but also don&#8217;t serve ads to crawlers. They just don&#8217;t buy your eBook or whatever you sell, unless a search engine sends out Web robots with credit cards able to understand Ajax, respectively authorized to fill out and submit Web forms.</p>
<p>Your ads look plain ugly with dotted borders in firebrick, hence don&#8217;t apply rel=&#8221;nofollow&#8221; to links when the requestor is not a search engine crawler. The engines are happy with machine-readable disclosures, and you can discuss everything else with the FTC yourself.</p>
<p>No nay never use links or content provided by affiliate programs on your pages. Encapsulate this kind of content delivery in AdServers. </p>
<p>Do not allow search engine crawlers to follow your affiliate links, paid links, nor other disliked votes as per search engine guidelines. Of course condomizing such links is not your responsibility, but getting penalized for not doing Google&#8217;s job is not exactly funny.</p>
<p>I admit that some of the stuff above is for extremely paranoid folks only, but knowing how to be paranoid might prevent you from making silly mistakes. Just because you believe that you&#8217;re not paranoid, that does not mean Google will not chase you down. You really don&#8217;t need to be a so called black hat to displease Google. Not knowing respectively not understanding <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=35769">Google&#8217;s 12 commandments</a> doesn&#8217;t prevent you from being spanked for sins you&#8217;ve never heard of. If you&#8217;re keen on Google&#8217;s nicely targeted traffic, better play by Google&#8217;s rules, leastwise on creawler requests.</p>
<p>Feel free to contribute your tips and tricks in the comments.</p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/linking-guide-for-paranoid-affiliate-marketers/", "style": "big", "title": "Act out your sophisticated affiliate link paranoia" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/linking-guide-for-paranoid-affiliate-marketers/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The anatomy of a server sided redirect: 301, 302 and 307 illuminated SEO wise</title>
		<link>http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/</link>
		<comments>http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#comments</comments>
		<pubDate>Tue, 09 Oct 2007 14:57:53 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[Web development]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[Cloaking]]></category>

		<category><![CDATA[.htaccess]]></category>

		<category><![CDATA[Yahoo]]></category>

		<category><![CDATA[SEO]]></category>

		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/</guid>
		<description><![CDATA[
We find redirects on every Web site out there. They&#8217;re often performed unnoticed in the background, unintentionally messed up, implemented with a great deal of ignorance, but seldom perfect from a SEO perspective. Unfortunately, the Webmaster boards are flooded with contradictorily, misleading and plain false  advice on redirects. If you for example read &#8220;for [...]]]></description>
			<content:encoded><![CDATA[
<p><img src="http://sebastians-pamphlets.com/img/posts/http-redirects.png" width="200" height="150" alt="HTTP Redirects" title="HTTP Redirects" style="margin-left:3px;" align="right"  />We find redirects on every Web site out there. They&#8217;re often performed unnoticed in the background, unintentionally messed up, implemented with a great deal of ignorance, but seldom perfect from a SEO perspective. Unfortunately, the Webmaster boards are flooded with contradictorily, misleading and plain false  advice on redirects. If you for example read &#8220;for SEO purposes you must make use of 301 redirects only&#8221; then better close the browser window/tab to prevent you from crappy advice. A 302 or 307 redirect can be search engine friendly too.</p>
<p>With this post I do plan to bore you to death. So lean back, grab some popcorn, and stay tuned for a longish piece explaining the Interweb&#8217;s forwarding requests as dull as dust. Or, if you know everything about redirects, then please digg, sphinn and stumble this post before you surf away. Thanks.</p>
<ul id="redirect-jump-station" style="margin-bottom:25px;"><b>Jump Station</b></p>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#post-203">The anatomy of a server sided redirect</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#http-redirect-def">Redirects are defined in the HTTP protocol, not in search engine guidelines</a></li>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#whats-a-ss-redirect">What is a server sided redirect?</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#exec-ss-redirect">Execution of server sided redirects</a></li>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#http-redirect-header">What is an HTTP redirect header?</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#http-status-line">The redirect response code in a HTTP status line</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#http-header-location">The redirect header&#8217;s &#8220;location&#8221; directive</a></li>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#how-to-implement-ss-redirect">How to implement a server sided redirect?</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#redirect-server-config">Redirects in server configuration files</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#redirect-dir-files-htaccess">Redirecting directories and files with .htaccess</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#redirect-in-scripts">Redirects in server sided scripts</a></li>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#invisible-server-redirects">Redirects done by the Web server itself</a></li>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#redirect-or-not">Redirect or not? A few use cases&#8230;</a></li>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#choosing-a-redirect-response-code">Choosing the best redirect response code (301, 302, or 307)</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#301-moved-permanently">301 - Moved Permanently</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#moving-sites-301">Moving sites with 301 redirects</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#302-found-elsewhere">302 - Found [Elsewhere]</a></li>
<li class="toc-h4"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#307-temporary-redirect">307 - Temporary Redirect</a></li>
<li class="toc-h3"><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#redirect-recap">Recap</a></li>
</ul>
<h4 id="http-redirect-def">Redirects are defined in the HTTP protocol, not in search engine guidelines</h4>
<p>For the moment please forget everything you&#8217;ve heard about redirects and their SEO implications, clear your mind, and follow me to the very basics defined in the HTTP protocol. Of course search engines interpret some redirects in a non-standard way, but understanding the norm as well as its use and abuse is necessary to deal with server sided redirects. I don&#8217;t bother with outdated HTTP 1.0 stuff, although some search engines still apply it every once in a while, hence I&#8217;ll discuss the 307 redirect introduced in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">HTTP 1.1</a> too. For information on client sided redirects please refer to <a href="http://sebastians-pamphlets.com/google-and-yahoo-treat-undelayed-meta-refresh-as-301-redirect/">Meta Refresh - the poor man&#8217;s 301 redirect</a> or read my other <a href="http://sebastians-pamphlets.com/links/categories/?cat=redirects">pamphlets on redirects</a>, and stay away from <a href="http://sebastians-pamphlets.com/links/categories/?cat=javascript-redirects">JavaScript URL manipulations</a>.</p>
<h3 id="whats-a-ss-redirect">What is a server sided redirect?</h3>
<p>Think about an HTTP redirect as a forwarding request. Although redirects work slightly different from snail mail forwarding requests, this analogy perfectly fits the <em>procedure</em>. Whilst with <a href="https://moversguide.usps.com/?referral=USPS">US Mail forwarding requests</a> a clerk or postman writes the new address on the envelope before it bounces in front of a no longer valid respectively temporarily abandoned letter-box or pigeon hole, on the Web the request&#8217;s location (that is the Web server responding to the <em>server name</em> part of the URL) provides the requestor with the new location (absolute URL). </p>
<p>A server sided redirect tells the user agent (browser, Web robot, &#8230;) that it has to perform another request for the URL given in the HTTP header&#8217;s &#8220;location&#8221; line in order to fetch the requested contents. The type of the redirect (301, 302 or 307) also instructs the user agent how to perform future requests of the Web resource. Because search engine crawlers/indexers try to emulate human traffic with their content requests, it&#8217;s important to choose the right redirect type both for humans and robots. That does not mean that a 301-redirect is always the best choice, and it certainly does not mean that you always must return the same HTTP response code to crawlers and browsers. More on that later.</p>
<h4 id="exec-ss-redirect">Execution of server sided redirects</h4>
<p>Server sided redirects are executed <b>before</b> your server delivers any content. In other words, your server ignores everything it <b>could</b> deliver (be it a static HTML file, a script output, an image or whatever) when it runs into a redirect condition. Some redirects are done by the server itself (see <a href="http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/#incomplete-uri">handling incomplete URIs</a>), and there are several places where you can set (conditional) redirect directives: Apache&#8217;s <a href="http://httpd.apache.org/docs/2.2/configuring.html">httpd.conf</a>, <a href="http://httpd.apache.org/docs/2.2/howto/htaccess.html">.htaccess</a>, or in application layers for example in <a href="http://www.php.net/manual/en/function.header.php">PHP scripts</a>. (If you suffer from IIS/ASP maladies, <a href="http://www.cumbrowski.com/CarstenC/seo_301redirect_aspsrc.asp">this post</a> is for you.) <b>Examples:</b></p>
<table cellpadding="1" cellspacing="0" border="1" bordercolor="gray">
<tr>
<th><b>Browser Request:</b></th>
<th><code><b>ww.site.com<br />/page.php?id=1</b></code></th>
<th><code><b>site.com<br />/page.php?id=1</b></code></th>
<th><code><b>www.site.com<br />/page.php?id=1</b></code></th>
<th><code><b>www.site.com<br />/page.php?id=2</b></code></th>
</tr>
<tr>
<td><b>Apache:</b></td>
<td>301 header:<br /><code>www.site.com<br />/page.php?id=1</code></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><b>.htaccess:</b></td>
<td>&nbsp;</td>
<td>301 header:<br /><code>www.site.com<br />/page.php?id=1</code></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td><b>/page.php:</b></td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td valign="top">301 header:<br /><code>www.site.com<br />/page.php?id=2</code></td>
<td valign="top">200 header:<br /><code>(Info like content length...)</code><br />
<hr />Content:<br />Article #2</td>
</tr>
</table>
<p>The 301 header may or may not be followed by a hyperlink pointing to the new location, solely added for user agents which can&#8217;t handle redirects. Besides that link, there&#8217;s no content sent to the client <b>after</b> the redirect header.</p>
<p>More important, you must not send a single byte to the client <b>before</b> the HTTP header. If you for example code <code>[space(s)|tab|new-line|HTML code]&lt;?php ...</code> in a script that shall perform a redirect or is supposed to return a 404 header (or any HTTP header different from the server&#8217;s default instructions), you&#8217;ll produce a runtime error. The redirection fails, leaving the visitor with an ugly page full of cryptic error messages but no link to the new location.</p>
<p>That means in each and every page or script which possibly has to deal with the HTTP header, put the logic testing those conditions at the very top. <strong>Always send the header status code and optional further information like a new location to the client before you process the contents.</strong> </p>
<p>After the last redirect header line terminate execution with the &#8220;L&#8221; parameter in .htaccess, PHP&#8217;s <code>exit;</code> statement, or whatever.</p>
<h3 id="http-redirect-header">What is an HTTP redirect header?</h3>
<p>An HTTP redirect, regardless its type, consists of two lines in the HTTP header. In this example I&#8217;ve requested http://www.sebastians-pamphlets.com/about/, which is an invalid URI because my server name lacks the www-thingy, hence my canonicalization routine outputs this HTTP header:</code><br />
<b>HTTP/1.1 301 Moved Permanently</b><br />
<span style="color:gray;">Date: Mon, 01 Oct 2007 17:45:55 GMT<br />
Server: Apache/1.3.37 (Unix) PHP/4.4.4</span><br />
<b>Location: http://sebastians-pamphlets.com/about/</b><br />
<span style="color:gray;">Connection: close<br />
Transfer-Encoding: chunked<br />
Content-Type: text/html; charset=iso-8859-1</span></code></p>
<h4 id="http-status-line">The redirect response code in a HTTP status line</h4>
<p>The first line of the header defines the protocol version, the reponse code, and provides a human readable reason phrase. Here is a shortened and slightly modified excerpt quoted from the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html#sec6">HTTP/1.1 protocol definition</a>:<br />
<blockquote><b>Status-Line</b></p>
<p>The first line of a <em>Response message</em> is the Status-Line, consisting of the protocol version followed by a numeric status code and its associated textual phrase, with each element separated by <acronym title="Space, blank, ASCII 0x20">SP</acronym> (space) characters. No <acronym title="Carriage Return, ASCII 0x0D">CR</acronym> or <acronym title="Line Feed, ASCII 0x0A">LF</acronym> is allowed except in the final <acronym title="New Line, CR followed by LF">CRLF</acronym> sequence.</p>
<p>Status-Line = HTTP-Version <i>SP</i> Status-Code <i>SP</i> Reason-Phrase <i>CRLF</i><br />
[e.g. &#8220;HTTP/1.1 301 Moved Permanently&#8221; + CRLF]</p>
<p><b>Status Code and Reason Phrase</b></p>
<p>The Status-Code element is a 3-digit integer result code of the attempt to understand and satisfy the request. [&#8230;] The Reason-Phrase is intended to give a short textual description of the Status-Code. The Status-Code is intended for use by automata and the Reason-Phrase is intended for the human user. The client is not required to examine or display the Reason-Phrase.</p>
<p>The first digit of the Status-Code defines the class of response. The last two digits do not have any categorization role. [&#8230;]:<br />
[&#8230;]<br />
- <b>3xx</b>: Redirection - Further action must be taken in order to complete the request<br />
[&#8230;]</p>
<p>The individual values of the numeric status codes defined for HTTP/1.1, and an example set of corresponding Reason-Phrases, are presented below. The reason phrases listed here are only recommendations &#8212; they MAY be replaced by local equivalents without affecting the protocol [that means you could translate and/or rephrase them].<br />
[&#8230;]<br />
<span style="color:gray;">300: Multiple Choices</span><br />
<b>301: Moved Permanently</b><br />
<b>302: Found [Elsewhere]</b><br />
<span style="color:gray;">303: See Other<br />
304: Not Modified<br />
305: Use Proxy</span><br />
<b>307: Temporary Redirect</b><br />
[&#8230;]</p></blockquote>
<p>In terms of SEO the understanding of 301/302-redirects is important. 307-redirects, introduced with HTTP/1.1, are still capable to confuse some search engines, even major players like Google when Ms. Googlebot for some reasons thinks she <em>must</em> do HTTP/1.0 requests, usually caused by weird respectively ancient server configurations (or possibly testing newly discovered sites under certain circumstances). You should not perform 307 redirects as response to most HTTP/1.0 requests, use 302/301 &#8211;whatever fits best&#8211; instead. More info on this issue below in the 302/307 sections.</p>
<p>Please note that the default reponse code of all redirects is 302. That means when you send a HTTP header with a location directive but without an explicit response code, your server will return a 302-Found status line. That&#8217;s kinda crappy, because in most cases you want to avoid the 302 code like the plague. Do no nay never rely on default response codes! <strong>Always prepare a server sided redirect with a status line telling an actual response code (301, 302 or 307)!</strong> In server sided scripts (PHP, Perl, ColdFusion, JSP/Java, ASP/VB-Script&#8230;) always send a complete status line, and in .htaccess or httpd.conf add a <code>[R=301|302|307<span style="color:gray;">,L</span>]</code> parameter to statements like <code>RewriteRule</code>: <code><br />
RewriteRule (.*) http://www.site.com/$1 [R=301,L]</code></p>
<h4 id="http-header-location">The redirect header&#8217;s &#8220;location&#8221; field</h4>
<p>The next element you need in every redirect header is the <b>location</b> directive. Here is the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.30">official syntax</a>:<br />
<blockquote>
<b>Location</b></p>
<p>The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. [&#8230;] For 3xx responses, the location SHOULD indicate the server&#8217;s preferred URI for automatic redirection to the resource. The field value consists of a single absolute URI.</p>
<p>Location = &#8220;Location&#8221; &#8220;:&#8221; absoluteURI [+ CRLF]</p>
<p>An example is:<br />
<code><br />
Location: http://sebastians-pamphlets.com/about/</code></p></blockquote>
<p><img src="http://sebastians-pamphlets.com/img/posts/redirect-to-an-absolute-url.png" width="200" height="150" alt="Redirect to absolute URLs only" title="A redirect's location is ALWAYS an absolute URL!" style="margin-left:3px;" align="right"  />Please note that the value of the location field must be an <b>absolute URL</b>, that is a fully qualified URL with scheme (http|https), server name (domain|subdomain), and path (directory/file name) plus the optional query string (&#8221;?&#8221; followed by variable/value pairs like <code>?id=1&amp;page=2...</code>), no longer than 2047 bytes (better 255 bytes because most scripts out there don&#8217;t process longer URLs <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.2.1">for historical reasons</a>). A relative URL like <code>../page.php</code> <em>might</em> work in (X)HTML (although you better plan a spectacular suicide than any use of relative URIs!), but <strong>you must not use relative URLs in HTTP response headers</strong>!</p>
<h3 id="how-to-implement-ss-redirect">How to implement a server sided redirect?</h3>
<p>You can perform HTTP redirects with statements in your Web server&#8217;s configuration, and in server sided scripts, e.g. PHP or Perl. JavaScript is a client sided language and therefore lacks a mechanism to do HTTP redirects. That means all JS redirects count as a 302-Found response.</p>
<p>Bear in mind that when you redirect, you possibly leave tracks of outdated structures in your HTML code, not to speak of incoming links. You must change each and every internal link to the new location, as well as all external links you control or where you can ask for an URL update. If you leave any outdated links, visitors probably don&#8217;t spot it (although every redirect slows things down), but search engine spiders continue to follow them, what ends in <a href="http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/">redirect chains</a> eventually. Chained redirects often are the cause of deindexing pages, site areas or even complete sites by search engines, hence do no more than one redirect in a row and consider two redirects in a row risky. You don&#8217;t control offsite redirects, in some cases a search engine has already counted one or two redirects before it requests your redirecting URL (caused by redirecting traffic counters etcetera). <b>Always redirect to the final destination to avoid useless hops which kill your search engine traffic.</b> (<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40132">Google recommends</a> &#8220;that you use fewer than five redirects for each request&#8221;, but don&#8217;t try to max out such limits because other services might be less BS-tolerant.)</p>
<p>Like conventional forwarding requests, redirects do expire. Even a permanent 301-redirect&#8217;s source URL will be requested by search engines every now and then because they can&#8217;t trust you. As long as there is one single link pointing to an outdated and redirecting URL out there, it&#8217;s not forgotten. It will stay alive in search engine indexes and address books of crawling engines even when the last link pointing to it was changed or removed. You can&#8217;t control that, and you can&#8217;t find all inbound links a search engine knows, despite their better reporting nowadays (neither <a href="https://siteexplorer.search.yahoo.com/">Yahoo&#8217;s site explorer</a> nor <a href="https://www.google.com/webmasters/tools/siteoverview">Google&#8217;s link stats</a> show you all links!). That means <b>you must maintain your redirects forever, and you must not remove (permanent) redirects</b>. Maintenance of redirects includes hosting abandoned domains, and updates of location directives whenever you change the final structure. <b>With each and every revamp that comes with URL changes check for incoming redirects and make sure that you eliminate unnecessary hops.</b></p>
<p>Often you&#8217;ve many choices where and how to implement a particular redirect. You can do it in scripts and even static HTML files, CMS software, or in the server configuration. There&#8217;s no such thing as a general best practice, just a few hints to bear in mind.
<ul>
<li><img src="http://sebastians-pamphlets.com/img/posts/redirects-are-dynamite-so-blast-carefully.png" width="150" height="164" alt="Redirects are dynamite, so blast carefully" title="SEO wise, the best redirect is no redirect at all!" style="margin-left:3px;" align="right"  /><b>Doubt</b>: Don&#8217;t believe Web designers and developers when they say that a particular task can&#8217;t be done without redirects. Do your own research, or ask an SEO expert. When you for example plan to make a static site dynamic by pulling the contents from a database with PHP scripts, you don&#8217;t need to change your file extensions from *.html to *.php. Apache can parse .html files for PHP, just enable that in your root&#8217;s .htaccess: <code><br />
AddType application/x-httpd-php .html <span style="color:gray;">.htm .shtml .txt .rss .xml .css</span></code><br />
Then generate tiny PHP scripts calling the CMS to replace the outdated .html files. That&#8217;s not perfect but way better than URL changes, provided your developers can manage the outdated links in the CMS&#8217; navigation. Another pretty popular abuse of redirects is click tracking. You don&#8217;t need a redirect script to count clicks in your database, <a href="http://sebastians-pamphlets.com/how-to-turn-click-tracking-into-miserable-failure/">make use of the onclick event instead</a>. </li>
<li><b>Transparency</b>: When the shit hits the fan and you need to track down a redirect with not more than the HTTP header&#8217;s information in your hands, you&#8217;ll begin to believe that performance and elegant coding is not everything. Reading and understanding a large httpd.conf file, several complex .htaccess files, and searching redirect routines in a conglomerate of a couple generations of scripts and include files is not exactly fun. You could add a custom field identifying the piece of redirecting code to the HTTP header. In .htaccess that would be achieved with <code><br />
Header add X-Redirect-Src &quot;/content/img/.htaccess&quot;</code><br />
and in PHP with <code><br />
header(&quot;X-Redirect-Src: /scripts/inc/header.php&quot;, TRUE);</code><br />
(Whether or not you should encode or at least obfuscate code locations in headers depends on your security requirements.) </li>
<li><b>Encapsulation</b>: When you must implement redirects in more than one script or include file, then encapsulate all redirects including all the logic (redirect conditions, determining new locations, &#8230;). You can do that in an include file with a meaningful file name for example. Also, instead of plastering the root&#8217;s .htaccess file with tons of directory/file specific redirect statements, you can gather all requests for redirect candidates and call a script which tests the REQUEST_URI to execute the suitable redirect. In .htaccess put something like:<code><br />
RewriteEngine On<br />
RewriteBase /old-stuff<br />
RewriteRule ^(.*)\.html$ do-redirects.php</code><br />
This code calls /old-stuff/do-redirects.php for each request of an .html file in /old-stuff/. The PHP script: <code><br />
$requestUri = $_SERVER[&quot;REQUEST_URI&quot;];<br />
if (stristr($requestUri, &quot;/contact.html&quot;)) {<br />
    $location = &quot;http://example.com/new-stuff/contact.htm&quot;;<br />
}<br />
...<br />
if ($location) {<br />
    @header(&quot;HTTP/1.1 301 Moved Permanently&quot;, TRUE, 301);<br />
    @header(&quot;X-Redirect-Src: /old-stuff/do-redirects.php&quot;, TRUE);<br />
    @header(&quot;Location: $location&quot;);<br />
    exit;<br />
}<br />
else {<br />
    [output the requested file or whatever]<br />
}</code><br />
(This is also an example of a redirect include file which you could insert at the top of a header.php include or so. In fact, you can include this script in some files <em>and</em> call it from .htaccess without modifications.) This method will not work with ASP on IIS because amateurish wannabe Web servers don&#8217;t provide the REQUEST_URI variable.</li>
<li><b>Documentation</b>: When you design or update an information architecture, your documentation should contain a redirect chapter. Also comment all redirects in the source code (your genial regular expressions might lack readability when someone else looks at your code). It&#8217;s a good idea to have a documentation file explaining all redirects on the Web server (you might work with other developers when you change your site&#8217;s underlying technology in a few years).</li>
<li><b>Maintenance</b>: Debugging legacy code is a nightmare. And yes, what you write today becomes legacy code in a few years. Thus keep it simple and stupid, implement redirects transparent rather than elegant, and don&#8217;t forget that you must change your ancient redirects when you revamp a site area which is the target of redirects.</li>
<li><b>Performance</b>: Even when performance is an issue, you can&#8217;t do everything in httpd.conf. When you for example move a large site changing the URL structure, the redirect logic becomes too complex in most cases. You can&#8217;t do database lookups and stuff like that in server configuration files. However, some redirects like for example server name canonicalization should be performed there, because they&#8217;re simple and not likely to change. If you can&#8217;t change httpd.conf, .htaccess files are for you. They&#8217;re are slower than cached config files but still faster than application scripts.</li>
</ul>
<h4 id="redirect-server-config">Redirects in server configuration files</h4>
<p>Here is an example of a canonicalization redirect in the root&#8217;s .htaccess file: <code><br />
RewriteEngine On<br />
RewriteCond %{HTTP_HOST} !^sebastians-pamphlets\.com [NC]<br />
RewriteRule (.*) http://sebastians-pamphlets.com/$1 [R=301,L]</code>
<ol>
<li>The first line enables Apache&#8217;s mod_rewrite module. Make sure it&#8217;s available on your box before you copy, paste and modify the code above.</li>
<li>
<p>The second line checks the server name in the HTTP request header (received from a browser, robot, &#8230;). The &#8220;NC&#8221; parameter ensures that the test of the server name (which is, like the scheme part of the URI, not case sensitive by <a href="http://www.ietf.org/rfc/rfc2396.txt">definition</a>) is done as intended. Without this parameter a request of http://SEBASTIANS-PAMPHLETS.COM/ would run in an unnecessary redirect. The rewrite condition returns TRUE when the server name is <b>not</b> sebastians-pamphlets.com. There&#8217;s an important detail: <b>not</b> &#8220;!&#8221; </p>
<p>Most Webmasters do it the other way round. They check if the server name equals an unwanted server name, for example with <code>RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]</code>. That&#8217;s not exactly efficient, and fault-prone. It&#8217;s not efficient because one needs to add a rewrite condition for each and every server name a user could type in and the Web server would respond to. On most machines that&#8217;s a huge list like &#8220;w.example.com, ww.example.com, w-w-w.example.com, &#8230;&#8221; because the default server configuration catches all not explicitely defined subdomains. </p>
<p>Of course next to nobody puts that many rewrite conditions into the .htaccess file, hence this method is fault-prone and not suitable to fix canonicalization issues. In combination with thoughtlessly usage of relative links (bullcrap that most designers and developers love out of lazyness and lack of creativity or at least fantasy), one single link to an existing page on a non-exisiting subdomain not redirected in such an .htaccess file could result in search engines crawling and possibly even indexing a complete site under the unwanted server name. When a <a href="http://fantomaster.com/fantomNews/archives/2007/07/20/negative-seo-inverse-seo-or-black-seo-whats-it-to-be/">savvy competitor</a> spots this exploit you can say good bye to a fair amount of your search engine traffic.</p>
<p>Another advantage of my single line of code is that you can point all domains you&#8217;ve registered to catch type-in traffic or whatever to the same Web space. Every new domain runs into the canonicalization redirect, 100% error-free.</p>
</li>
<li>The third line performs the 301 redirect to the requested URI using the canonical server name. That means when the request URI was http://www.sebastians-pamphlets.com/about/, the user agent gets redirected to http://sebastians-pamphlets.com/about/. The &#8220;R&#8221; parameter sets the reponse code, and the &#8220;L&#8221; parameter means <em>leave if the</em>|<em>one condition matches</em> (=exit), that is the statements following the redirect execution, like other rewrite rules and such stuff, will not be parsed.</li>
</ol>
<p>If you&#8217;ve access to your server&#8217;s httpd.conf file (what most hosting services don&#8217;t allow), then better do such redirects there. The reason for this recommendation is that Apache must look for .htaccess directives in the current directory and all its upper levels for each and every requested file. If the request is for a page with lots of embedded images or other objects, that sums up to hundreds of hard disk accesses slowing down the page loading time. The server configuration on the other hand is cached and therefore way faster. Learn more about <a href="http://httpd.apache.org/docs/2.2/howto/htaccess.html#when">.htaccess disadvantages</a>. However, since most Webmasters can&#8217;t modify their server configuration, I provide .htaccess examples only. If you can do, then you know how to put it in httpd.conf. <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h4 id="redirect-dir-files-htaccess">Redirecting directories and files with .htaccess</h4>
<p>When you need to redirect chunks of static pages to another location, the easiest way to do that is Apache&#8217;s <a href="http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect">redirect directive</a>. The basic syntax is <code>Redirect [301|302|307] Path URL</code>, e.g. <code>Redirect 307 /blog/feed http://feedburner.com/myfeed</code> or <code>Redirect 301 /contact.htm /blog/contact/</code>. <code>Path</code> is always a file system path relative to the Web space&#8217;s root. <code>URL</code> is either a fully qualified URL (on another machine) like http://feedburner.com/myfeed, or a relative URL on the same server like /blog/contact/ (Apache adds scheme and server in this case, so that the HTTP header is build with an absolute URL in the location field; however, omitting the scheme+server part of the target URL is not recommended, see the warning below).</p>
<p>When you for example want to consolidate a blog on its own subdomain and a corporate Web site at example.com, then put <code><br />
 Redirect 301 / http://example.com/blog</code><br />
in the .htacces file of blog.example.com. When you then request http://blog.example.com/category/post.html you&#8217;re redirected to http://example.com/blog/category/post.html.</p>
<p>Say you&#8217;ve moved your product pages from /products/*.htm to /shop/products/*.htm then put <code><br />
Redirect 301 /products http://example.com/shop/products</code></p>
<p>Omit the trailing slashes when you redirect directories. To redirect particular files on the other hand you must fully qualify the locations: <code><br />
Redirect 302 /misc/contact.html http://example.com/cms/contact.php</code><br />
or, when the new location resides on the same server: <code><br />
Redirect 301 /misc/contact.html /cms/contact.php</code></p>
<p><b style="color:red;">Warning:</b> Although Apache allows local redirects like <code>Redirect 301 /misc/contact.html /cms/contact.php</code>, with some server configurations this will result in 500 server errors on all requests. Therefore I recommend the use of fully qualified URLs as redirect target, e.g. <code>Redirect 301 /misc/contact.html <b>http://example.com</b>/cms/contact.php</code>!</p>
<p>Maybe you found a reliable and unbeatable cheap hosting service to host your images. Copy all image files from example.com to image-example.com and keep the directory structures as well as all file names. Then add to example.com&#8217;s .htaccess <code><br />
RedirectMatch 301 (.*)\.([Gg][Ii][Ff]|[Pp][Nn][Gg]|[Jj][Pp][Gg])$ http://www.image-example.com$1.$2</code><br />
The regex should match e.g. <code>/img/nav/arrow-left.png</code> so that the user agent is forced to request http://www.image-example.com<b>/img/nav/arrow-left.png</b>. Say you&#8217;ve converted your GIFs and JPGs to the PNG format during this move, simply change the redirect statement to <code><br />
RedirectMatch 301 (.*)\.([Gg][Ii][Ff]|[Pp][Nn][Gg]|[Jj][Pp][Gg])$ http://www.image-example.com$1.png</code><br />
With regular expressions and <a href="http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirectmatch">RedirectMatch</a> you can perform very creative redirects.</p>
<p>Please note that the response codes used in the code examples above most probably do not fit the type of redirect you&#8217;d do in real life with similar scenarios. I&#8217;ll discuss use cases for all redirect response codes (301|302|307) later on.</p>
<h4 id="redirect-in-scripts">Redirects in server sided scripts</h4>
<p>You can do HTTP redirects only with server sided programming languages like PHP, ASP, Perl etcetera. Scripts in those languages generate the output before anything is send to the user agent. It should be a no-brainer, but these PHP examples don&#8217;t count as server sided redirects: <code><br />
print &quot;&lt;META HTTP-EQUIV=Refresh CONTENT=&quot;0; URL=http://example.com/&quot;&gt;\n&quot;;<br />
print &quot;&lt;script type="text/javascript"&gt;window.location = &quot;http://example.com/&quot;;&lt;/script&gt;\n&quot;;</code><br />
Just because you can output a redirect with a server sided language that does not make the redirect an HTTP redirect. <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>In PHP you perform HTTP redirects with the <a href="http://www.php.net/manual/en/function.header.php">header() function</a>: <code><br />
$newLocation = &quot;http://example.com/&quot;;<br />
@header(&quot;HTTP/1.1 301 Moved Permanently&quot;, TRUE, 301);<br />
@header(&quot;Location: $newLocation&quot;);<br />
exit;</code><br />
The first input parameter of header() is the complete header line, in the first line of code above that&#8217;s the status-line. The second parameter tells whether a previously sent header line shall be replaced (default behavior) or not. The third parameter sets the HTTP status code, don&#8217;t use it more than once. If you use an ancient PHP version (prior 4.3.0) you can&#8217;t put the 2nd and 3rd input parameter. The &#8220;@&#8221; suppresses PHP warnings and error messages.</p>
<p>With ColdFusion you code <code><br />
&lt;CFHEADER statuscode=&quot;307&quot; statustext=&quot;Temporary Redirect&quot;&gt;<br />
&lt;CFHEADER name=&quot;Location&quot; value=&quot;http://example.com/&quot;&gt; </code></p>
<p>A redirecting Perl script begins with <code><br />
#!/usr/bin/perl -w<br />
use strict;<br />
print &quot;Status: 302 Found Elsewhere\r\n&quot;, &quot;Location: http://example.com/\r\n\r\n&quot;;<br />
exit; </code></p>
<p>Even with ASP you can do server sided redirects. VBScript: <code><br />
Dim newLocation<br />
newLocation = &quot;http://example.com/&quot;<br />
Response.Status = &quot;301 Moved Permanently&quot;<br />
Response.AddHeader &quot;Location&quot;, newLocation<br />
Response.End </code><br />
JScript: <code><br />
Function RedirectPermanent(newLocation) {<br />
Response.Clear();<br />
Response.Status = 301;<br />
Response.AddHeader(&quot;Location&quot;, newLocation);<br />
Response.Flush();<br />
Response.End();<br />
}<br />
...<br />
Response.Buffer = TRUE;<br />
...<br />
RedirectPermanent (&quot;http://example.com/&quot;); </code><br />
Again, if you suffer from IIS/ASP maladies: <a href="http://www.cumbrowski.com/CarstenC/seo_301redirect_aspsrc.asp">here you go</a>.</p>
<p><b><a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#exec-ss-redirect">Remember</a>: Don&#8217;t output anything before the redirect header, and nothing after the redirect header!</b></p>
<h3 id="invisible-server-redirects">Redirects done by the Web server itself</h3>
<p>When you read your raw server logs, you&#8217;ll find a few 302 and/or 301 redirects Apache has performed without an explicit redirect statement in the server configuration, .htaccess, or a script. Most of these automatic redirects are the result of a very popular bullshit practice: removing trailing slashes. Although the standard defines that an URI like <code>/directory</code> is not a file name by default, therefore equals <code>/directory/</code> if there&#8217;s no file named <code>/directory</code>, choosing the version without the trailing slash is lazy at least, and creates lots of troubles (404s in some cases, otherwise external redirects, but always duplicate content issues you should fix with URL canonicalization routines). </p>
<p>For example Yahoo is a big fan of truncated URLs. They might save a few terabytes in their indexes by storing URLs without the trailing slash, but they send every user&#8217;s browser twice to those locations. Web servers must do a 302 or 301 redirect on each Yahoo-referrer requesting a directory or pseudo-directory, because they can&#8217;t serve the default document of an omitted path segment (the path component of an URI begins with a slash, the slash is its segment delimiter, and a trailing slash stands for the last (or only) segment representing a default document like index.html). From the Web server&#8217;s perspective <code>/directory</code> does not equal <code>/directory/</code>, only <code>/directory/</code> addresses <code>/directory/index.(htm|html|shtml|php|...)</code>, whereby the file name of the default document must be omitted (among other things to preserve the URL structure when the underlying technology changes). Also, the requested URI without its trailing slash <em>may</em> address a file or an on the fly output (if you make use of mod_rewrite to mask ugly URLs you better test what happens with screwed URIs of yours). </p>
<p>Yahoo wastes even their own resources. Their crawler persistently requests the shortened URL, what bounces with a redirect to the canonical URL. Here is an example from my raw logs: <code style="font-size:90%;"><br />
74.6.20.165 - - [05/Oct/2007:01:13:04 -0400] "GET <b>/directory</b> HTTP/1.0&#8243; 301 26 &#8220;-&#8221; &#8220;Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)&#8221;<br />
74.6.20.165 - - [05/Oct/2007:01:13:06 -0400] &#8220;GET <b>/directory/</b> HTTP/1.0&#8243; 200 8642 &#8220;-&#8221; &#8220;Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)&#8221;<br />
[I&#8217;ve replaced a rather long path with &#8220;directory&#8221;]</code><br />
If you persistently redirect Yahoo to the canonical URLs (with trailing slash), they&#8217;ll use your canonical URLs on the SERPs eventually (but their crawler still requests Yahoo-generated crap). Having many good inbound links as well as clean internal links &#8211;all with the trailing slash&#8211; helps too, but is not a guarantee for canonical URL normalization at Yahoo. </p>
<p>Here is an example. This URL responds with 200-OK, regardless whether it&#8217;s requested with or without the canonical trailing slash:<br />
<a href="http://www.jlh-design.com/2007/06/im-confused/">http://www.jlh-design.com/2007/06/im-confused<b>/</b></a><br />
(That&#8217;s the default (mis)behavior of everybody&#8217;s darling <a href="http://codex.wordpress.org/WordPress" rel="tag">WordPress</a> with permalinks by the way. Here is some <a href="http://sebastians-pamphlets.com/how-to-seo-sanitize-a-wordpress-theme/">PHP canonicalization code</a> to fix this flaw.) All internal links use the canonical URL. I didn&#8217;t find a serious inbound link pointing to a truncated version of this  URL. Yahoo&#8217;s Site Explorer lists the URL without the trailing slash: <a href="http://rds.yahoo.com/_ylt=AvoWb6YsAONIB5JuHEpx7hbal8kF/SIG=11iu4jphv/**http%3A//www.jlh-design.com/2007/06/im-confused">[&#8230;]/im-confused</a>, and the same happens on Yahoo&#8217;s SERPs: <a href="http://rds.yahoo.com/_ylt=A0geu7H1igdHzvUAJrxXNyoA;_ylu=X3oDMTFicXZvZGs5BHNlYwNzcgRwb3MDMQRjb2xvA2FjMgR2dGlkA01BUDAxNF8xMDAEbANXUzE-/SIG=121md4r95/EXP=1191763061/**http%3a//www.jlh-design.com/2007/06/im-confused">[&#8230;]/im-confused</a>. Even when a server responds 200-OK to two different URLs, a serious search engine should normalize according to the internal links as well as an entry in the XML sitemap, therefore choose the URL with the trailing slash as canonical URL. </p>
<p>Fucking up links on search result pages is evil enough, although fortunately this crap doesn&#8217;t influence discovery crawling directly because those aren&#8217;t crawled by other search engines (but scraped or syndicated search results <b>are</b> crawlable). Actually, that&#8217;s not the whole horror story. Other Yahoo properties remove the trailing slashes from directory and home page links too (look at the &#8220;What Readers Viewed&#8221; column in your MBL stats for example), and some of those services provide crawlable pages carrying invalid links (pulled from the search index or screwed otherwise). That means other search engines pick those incomplete URLs from Yahoo&#8217;s pages (or other pages with links copied from Yahoo pages), crawl them, and end up with search indexes blown up with duplicate content. Maybe Yahoo does all that only to burn Google&#8217;s resources by keeping their canonicalization routines and duplicate content filters busy, but it&#8217;s not exactly gentlemanlike that such cat fights affect all Webmasters across the globe. Yahoo directly as well as indirectly burns our resources with unnecessary requests of screwed URLs, and we must implement <a href="http://sebastians-pamphlets.com/how-to-seo-sanitize-a-wordpress-theme/">sanitizing redirects for software like WordPress</a> &#8211;which doesn&#8217;t care enough about URL canonicalization&#8211;, just because Yahoo manipulates our URLs to peeve Google. Doh!</p>
<p>If somebody from Yahoo (or MSN, or any other site manipulating URLs this way) reads my rant, I highly recommend this quote from <a href="http://gbiv.com/protocols/uri/rfc/rfc3986.html#rfc.section.6">Tim Berners-Lee</a> (January 2005):<br />
<blockquote><a href="http://gbiv.com/protocols/uri/rfc/rfc3986.html#rfc.section.6.2.3"><b>Scheme-Based Normalization</b></a><br />
[&#8230;] the following [&#8230;] URIs are equivalent:<br />
   http://example.com<br />
   http://example.com/<br />
In general, an URI that uses the generic syntax for authority with an empty path should be normalized to a path of &#8220;/&#8221;.<br />
[&#8230;]<br />
<b>Normalization should not remove delimiters</b> [&#8221;/&#8221; or &#8220;?&#8221;] <b>when their associated component is empty</b> unless licensed to do so by the scheme specification. [emphasis mine]</p></blockquote>
<p>In my book sentences like &#8220;Note that the absolute path cannot be empty; if none is present in the original URI, it MUST be given as &#8216;/&#8217; [&#8230;]&#8221; in the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html">HTTP specification</a> as well as Section 3.3 of the <a href="http://www.w3.org/TR/urispace" title="Section 3.3">URI&#8217;s Path Segment specs</a> do not sound like a licence to screw URLs. Omitting the path segment delimiter &#8220;/&#8221; representing an empty last path segment <em>might</em> sound legal if the specs are interpreted without applying common sense, but <em>knowing</em> that Web servers can&#8217;t respond to requests of those incomplete URIs and <em>nevertheless</em> truncating trailing slashes is a brain dead approach (actually, such crap deserves a couple unprintable adjectives). </p>
<p>Frequently scanning the raw logs for 302/301 redirects is a good idea. Also, <b>implement documented canonicalization redirects when a piece of software responds to different versions of URLs</b>. It&#8217;s the Webmaster&#8217;s responsibility to ensure that each piece of content is available under one and only one URL. You cannot rely on any search engine&#8217;s URL canonicalization, because shit happens, even with <a href="http://googlewebmastercentral.blogspot.com/2007/09/google-duplicate-content-caused-by-url.html">high sophisticated algos</a>:<br />
<blockquote>When search engines crawl identical content through varied URLs, there may be several negative effects:</p>
<p>1. Having multiple URLs can dilute link popularity. For example, in the <a href="http://googlewebmastercentral.blogspot.com/2007/09/google-duplicate-content-caused-by-url.html#BLOGGER_PHOTO_ID_5109718653929535858">diagram above</a> [example in Google&#8217;s blog post], rather than 50 links to your intended display URL, the 50 links may be divided three ways among the three distinct URLs.</p>
<p>2. Search results may display user-unfriendly URLs [&#8230;]</p></blockquote>
<h3 id="redirect-or-not">Redirect or not? A few use cases.</h3>
<p>Before I blather about the three redirect response codes you can choose from, I&#8217;d like to talk about a few situations where you shall not redirect, and cases where you probably don&#8217;t redirect but should do so. </p>
<p>Unfortunately, it&#8217;s a common practice to replace various sorts of clean links with redirects. Whilst legions of Webmasters don&#8217;t obfuscate their affiliate links, they hide their valuable outgoing links in fear of PageRank leaks and other myths, or react to search engine <acronym title="Fear, Uncertainty &amp; Doubt">FUD</acronym> with castrated links.</p>
<p>With very few exceptions, the <a href="http://www.smart-it-consulting.com/article.htm?node=155">A Element a.k.a. Hyperlink</a> is the best method to transport link juice (PageRank, topical relevancy, trust, reputation &#8230;) as well as human traffic. Don&#8217;t abuse my beloved A Element: <code><br />
&lt;a onclick=&quot;window.location = &apos;http://example.com/&apos;; return false;&quot; title=&quot;http://example.com&quot;&gt;bad example&lt;/a&gt;</code><br />
Such a &#8220;link&#8221; will transport some visitors, but does not work when JavaScript is disabled or the user agent is a Web robot. This &#8220;link&#8221; is not an iota better: <code><br />
&lt;a href=&quot;http://example.com/blocked-directory/redirect.php?url=http://another-example.com/&quot; title=&quot;Another bad example&quot;&gt;example&lt;/a&gt;</code></p>
<p>Simplicity pays. You don&#8217;t need the complexity of HREF values changed to ugly URLs of redirect scripts with parameters, located in an uncrawlable path, just because you don&#8217;t want that search engines count the links. Not to speak of cases where redirecting links is unfair or even risky, for example click tracking scripts which do a redirect.
<ul>
<li>If you need to track outgoing traffic, then by all means do it in a search engine friendly way with clean URLs which benefit the link destination and don&#8217;t do you any harm, <a href="http://sebastians-pamphlets.com/how-to-turn-click-tracking-into-miserable-failure/">here is a proven method</a>.</li>
<li>If you really can&#8217;t vouch for a link, for example because you link out to a so called bad neighborhood (whatever that means), or to a link broker, or to someone who paid for the link and Google can detect it or a competitor can turn you in, then add <a href="http://www.smart-it-consulting.com/article.htm?node=155&#038;page=90#a-rel">rel=&#8221;nofollow&#8221;</a> to the link. Yeah, <a href="http://sebastians-pamphlets.com/links/categories/?cat=nofollow">rel-nofollow</a> is <a href="http://sebastians-pamphlets.com/links/categories/?cat=crap">crap</a> &#8230; but it&#8217;s there, it works, we won&#8217;t get something better, and it&#8217;s less complex than redirects, so just apply it to your fishy links as well as to unmoderated user input.</li>
<li>If you decide that an outgoing link adds value for your visitors, and you personally think that the linked page is a great resource, then almost certainly search engines will endorse the link (regardless whether it shows a toolbar PR or not). There&#8217;s way too much FUD and crappy advice out there.</li>
<li>You really don&#8217;t lose PageRank when you link out. Honestly gained PageRanks sticks at your pages. You only lower the amount of PageRank you can pass to your internal links a little. That&#8217;s not a bad thing, because linking out to great stuff can bring in more PageRank in the form of natural inbound links (there are other advantages too). Also, Google dislikes PageRank hoarding and the unnatural link patterns you create with practices like that.</li>
<li>Every redirect slows things down, and chances are that a user agent messes with the redirect what can result in rendering nil, scrambled stuff, or something completely unrelated. I admit that&#8217;s not a very common problem, but it happens with some outdated though still used browsers. <b>Avoid redirects where you can.</b></li>
</ul>
<p>In some cases you should perform redirects for sheer search engine compliance, in other words selfish SEO purposes. For example don&#8217;t let search engines handle your affiliate links.
<ul>
<li>If you operate an affiliate program, then internally redirect all incoming affiliate links to <a href="http://sebastians-pamphlets.com/google-recommends-screwing-affiliates-in-exchange-for-better-serp-positioning/">consolidate your landing page URLs</a>. Although incoming affiliate links don&#8217;t bring much link juice, every little helps when it lands on a page which doesn&#8217;t credit search engine traffic to an affiliate.</li>
<li>Search engines are pretty smart when it comes to identifying affiliate links. (Thin) affiliate sites suffer from decreasing search engine traffic. Fortunately, the engines respect <a href="http://sebastians-pamphlets.com/links/categories/?cat=robotstxt">robots.txt</a>, that means they usually don&#8217;t follow links via blocked subdirectories. When you link to your merchants within the content, using URLs that don&#8217;t smell like affiliate links, it&#8217;s harder to detect the intention of those links algorithmically. Of course that doesn&#8217;t prevent you from smart algos trained to spot other patterns, and this method will not pass reviews by humans, but it&#8217;s <a href="http://sebastians-pamphlets.com/google-recommends-screwing-affiliates-in-exchange-for-better-serp-positioning/" title="Read the comments too!">worth a try</a>.</li>
<li>If you&#8217;ve pages which change their contents often by featuring for example a product of the day, you might have a redirect candidate. Instead of duplicating a daily changing product page, you can do a dynamic soft redirect to the product pages. Whether a 302 or a 307 redirect is the best choice depends on the individual circumstances. However, you can promote the hell out of the redirecting page, so that it gains all the search engine love without passing on PageRank etc. to product pages which phase out after a while. (If the product page is hosted by the merchant you must use a 307 response code. Otherwise make sure the 302&#8242;ing URL ist listed in your XML sitemap with a high priority. If you can, send a 302 with most HTTP/1.0 requests, and a 307 responding to HTTP/1.1 requests. See the 302/307 sections for more information.)</li>
<li>If an URL comes with a session-ID or another tracking variable in its query string, you must 301-redirect search engine crawlers to an URI without such randomly generated noise. There&#8217;s no need to redirect a human visitor, but <a href="http://www.smart-it-consulting.com/article.htm?node=148&#038;page=103">search engines hate tracking variables</a> so just don&#8217;t let them fetch such URLs. </li>
<li>There are other use cases involving creative redirects which I&#8217;m not willing to discuss here.</li>
</ul>
<p>Of course both lists above aren&#8217;t complete.</p>
<h3 id="choosing-a-redirect-response-code">Choosing the best redirect response code (301, 302, or 307)</h3>
<p><img src="http://sebastians-pamphlets.com/img/posts/choosing-a-redirect-response-code-301-302-307.png" width="200" height="150" alt="Choosing a redirect response code" title="Which HTTP redirect response code fits my needs?" style="margin-left:3px;" align="right"  />I&#8217;m sick of articles like &#8220;search engine friendly 301 redirects&#8221; propagating that only permanant redirects work with search engines. That&#8217;s a lie. I read those misleading headlines daily on the webmaster boards, in my feed reader, at Sphinn, and elsewhere &#8230; and I&#8217;m not amused. Lemmings. Amateurish copycats. Clueless plagiarists. [Insert a few lines of somewhat offensive language and swearing <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ]</p>
<p>Of course most redirects out there return the wrong response code. That&#8217;s because the default HTTP response code for all redirects is 302, and many code monkeys forget to send a status-line providing the <b>301 Moved Permanantly</b> when an URL was actually moved or the requested URI is not the canonical URL. When a clueless coder or hosting service invokes a <code>Location: http://example.com/</code> header statement without a previous <code>HTTP/1.1 301 Moved Permanantly</code> status-line, the redirect becomes a soft <code>302 Found</code>. That does not mean that 302 or 307 redirects aren&#8217;t search engine friendly at all. All HTTP redirects can be safely used with regard to search engines. The point is that one must choose the correct response code based on the actual circumstances and goals. Blindly 301&#8242;ing everything is counterproductive sometimes.</p>
<h4 id="301-moved-permanently">301 - Moved Permanently</h4>
<p><img src="http://sebastians-pamphlets.com/img/posts/301-moved-permanently.png" width="200" height="101" alt="301 Moved Permanently" title="301 Moved Permanently" style="margin-left:3px;" align="right"  />The message of a 301 reponse code to the requestor is: &#8220;The requested URI has vanished. It&#8217;s gone forever and perhaps it never existed. I will <b>never</b> supply any contents under this URI (again). Request the URL given in location, and replace the outdated respectively wrong URL in your bookmarks/records by the new one for future requests. Don&#8217;t bother me again. Farewell.&#8221;</p>
<p>Lets start with the definition of a 301 redirect quoted from the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2">HTTP/1.1 specifications</a>:<br />
<blockquote>The requested resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs [<a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#301-uris">(1)</a>]. Clients with link editing capabilities ought to automatically re-link references to the Request-URI to one or more of the new references returned by the server, where possible. This response is cacheable unless indicated otherwise.</p>
<p>The new permanent URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s). [&#8230;]</p></blockquote>
<p>Read a polite &#8220;SHOULD&#8221; as &#8220;must&#8221;.</p>
<p><span id="301-uris">(1)</span> Although technically you <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.14">could</a> provide more than one location, you must not do that because it irritates too many user agents, search engine crawlers included. </p>
<p>Make use of the 301 redirect when a requested Web resource was moved to another location, or when a user agent requests an URI which is definitely wrong and you&#8217;re able to tell the correct URI with no doubt. For URL canonicalization purposes (<a href="http://sebastians-pamphlets.com/how-to-seo-sanitize-a-wordpress-theme/">more</a> <a href="http://www.mattcutts.com/blog/seo-advice-url-canonicalization/">info</a> <a href="http://www.mattcutts.com/blog/canonicalization-update/">here</a>) the 301 redirect is your one and only friend.</p>
<p>You must not recycle any 301&#8242;ing URLs, that means once an URL responds with 301 you must stick with it, you can&#8217;t reuse this URL for other purposes next year or so. </p>
<p>Also, you must maintain the 301 response and a location corresponding to the redirecting URL forever. That does not mean that the location can&#8217;t be changed. Say you&#8217;ve moved a contact page <code>/contact.html</code> to a CMS where it resides under <code>/cms/contact.php</code>. If a user agent requests <code>/contact.html</code> it does a 301 redirect pointing to <code>/cms/contact.php</code>. Two years later you change your software again, and the contact page moves to <code>/blog/contact/</code>. In this case you must change the initial redirect, and create a new one:<br />
<code>/contact.html</code> 301-redirects to <code>/blog/contact/</code>, and<br />
<code>/cms/contact.php</code> 301-redirects to <code>/blog/contact/</code>.<br />
If you keep the initial redirect <code>/contact.html</code> to <code>/cms/contact.php</code>, and redirect <code>/cms/contact.php</code> to <code>/blog/contact/</code>, you create a <a href="http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/">redirect chain which can deindex your content at search engines</a>. Well, two redirects before a crawler reaches the final URL shouldn&#8217;t be a big deal, but add a canonicalization redirect fixing a www vs. non-www issue to the chain, and imagine a crawler comes from a directory or links list which counts clicks with a redirect script, you&#8217;ve four redirects in a row. That&#8217;s too much, most probably all search engines will not index such an unreliable Web resource.</p>
<p>301 redirects transfer search engine love like PageRank gathered by the redirecting URL to the new location, but the search engines keep the old URL in their indexes, and revisit it every now and then to check whether the 301 redirect is stable or not. If the redirect is gone on the next crawl, the new URL loses the reputation earned from the redirect&#8217;s inbound links. It&#8217;s impossible to get all inbound links changed, hence don&#8217;t delete redirects after a move.</p>
<p>It&#8217;s a good idea to check your 404 logs weekly or so, because search engine crawlers pick up malformed links from URL drops and such. Even when the link is invalid, for example because a crappy forum software has shortened the URL, it&#8217;s an asset you should not waste with a 404 or even 410 response. Find the best matching existing URL and do a 301 redirect.</p>
<p>Here is what Google says about 301 redirects:<br />
<blockquote>
<p>[<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40151">Source</a>] 301 (Moved permanently) [&#8230;] You should use this code to let Googlebot know that a page or site has permanently moved to a new location. [&#8230;]</p>
<p>[<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=66359">Source</a> &#8230;] If you&#8217;ve restructured your site, use 301 redirects (&#8221;RedirectPermanent&#8221;) in your .htaccess file to smartly redirect users, Googlebot, and other spiders. (In Apache, you can do this with an .htaccess file; in IIS, you can do this through the administrative console.) [&#8230;]</p>
<p>[<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=34464">Source</a> &#8230;] If your old URLs redirect to your new site using HTTP 301 (permanent) redirects, our crawler will discover the new URLs. [&#8230;] Google listings are based in part on our ability to find you from links on other sites. To preserve your rank, you&#8217;ll want to tell others who link to you of your change of address. [&#8230;]</p>
<p>[<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=34481">Source</a> &#8230;] If your site [or page] is appearing as two different listings in our search results, we suggest consolidating these listings so we can more accurately determine your site&#8217;s [page&#8217;s] PageRank. The easiest way to do so [on site level] is to <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=44232">set the preferred domain using our webmaster tools</a>. You can also redirect one version [page] to the other [canonical URL] using a <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40151">301 redirect</a>. This should resolve the situation after our crawler discovers the change. [&#8230;]</p>
</blockquote>
<p>That&#8217;s exactly what the HTTP standard wants a search engine to do. Yahoo handles 301 redirects a little different:<br />
<blockquote>
<p>[<a href="http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-11.html">Source</a> &#8230;] When one web page redirects to another web page, Yahoo! Web Search sometimes indexes the page content under the URL of the entry or &#8220;source&#8221; page, and sometimes index it under the URL of the final, destination, or &#8220;target&#8221; page. [&#8230;]</p>
<p>When a page in one domain redirects to a page in another domain, Yahoo! records the &#8220;target&#8221; URL. [&#8230;]</p>
<p>When a top-level page [http://example.com/] in a domain presents a permanent redirect to a page deep within the same domain, Yahoo! indexes the &#8220;source&#8221; URL. [&#8230;]</p>
<p>When a page deep within a domain presents a permanent redirect to a page deep within the same domain, Yahoo! indexes the &#8220;target&#8221; URL. [&#8230;]</p>
<p>Because of mapping algorithms directing content extraction, Yahoo! Web Search is not always able to discard URLs that have been seen as 301s, so web servers might still see crawler traffic to the pages that have been permanently redirected. [&#8230;]</p>
</blockquote>
<p>As for the non-standard procedure to handle redirecting root index pages, that&#8217;s not a big deal, because in most cases a site owner promotes the top level page anyway. Actually, that&#8217;s a smart way to &#8220;break the rules&#8221; for the better. The way too many requests of permanently redirecting pages are more annoying.</p>
<h4 id="moving-sites-301">Moving sites with 301 redirects</h4>
<p>When you restructure a site, consolidate sites or separate sections, move to another domain, flee from a free host, or do other structural changes, then in theory you can install page by page 301 redirects and you&#8217;re done. Actually, that works but comes with disadvantages like a total loss of all search engine traffic for a while. As larger the site, as longer the while. With a large site highly dependent on SERP referrers this procedure can be the first phase of a filing for bankruptcy plan, because <em>all</em> search engines don&#8217;t send (much) traffic during the move.</p>
<p>Lets look at the process from a search engine&#8217;s perspective. The crawling of old.com all of a sudden bounces at 301 redirects to new.com. None of the redirect targets is known to the search engine. The crawlers report back redirect responses and the new URLs as well. The indexers spotting the redirects block the redirecting URLs for the query engine, but can&#8217;t pass the properties (PageRank, contextual signals and so on) of the redirecting resources to the new URLs, because those aren&#8217;t crawled yet. </p>
<p>The crawl scheduler initiates the handshake with the newly discovered server to estimate its robustness, and most propably does a conservative guess of the crawl frequency this server can sustain. The queue of uncrawled URLs belonging to the new server grows way faster than the crawlers actually deliver the first contents fetched from the new server. </p>
<p>Each and every URL fetched from the old server vanishes from the SERPs in no time, whilst the new URLs aren&#8217;t crawled yet, or are still waiting for an idle indexer able to assign them the properties of the old URLs, doing heuristic checks on the stored contents from both URLs and whatnot. </p>
<p>Slowly, sometimes weeks after the begin of the move, the first URLs from the new server populate the SERPs. They don&#8217;t rank very well, because the search engine has not yet discovered the new site&#8217;s structure and linkage completely, so that a couple of ranking factors stay temporairily unconsidered. Some of the new URLs may appear as URL-only listing, solely indexed based on off-page factors, hence lacking the ability to trigger search query relevance for their contents. </p>
<p>Many of the new URLs can&#8217;t regain their former PageRank in the first reindexing cycle, because without a complete survey of the &#8220;new&#8221; site&#8217;s linkage there&#8217;s only the PageRank from external inbound links passed by the redirects available (internal links no longer count for PageRank when the search engine discovers that the source of internally distributed PageRank does a redirect), so that they land in a secondary index. </p>
<p>Next, the suddenly lower PageRank results in a lower crawling frequency for the URLs in question. Also, the process removing redirecting URLs still runs way faster than the reindexing of moved contents from the new server. As more URLs are involved in a move, as longer the reindexing and reranking lasts. Replace Google&#8217;s very own PageRank with any term and you&#8217;ve a somewhat usable description of a site move handled by Yahoo, MSN, or Ask. There are only so many ways to handle such a challenge.</p>
<p>That&#8217;s a horror scenario, isn&#8217;t it? Well, at Google the recently changed infrastructure has greatly improved this process, and other search engines evolve too, but moves as well as significant structural changes will always result in periods of decreased SERP referrers, or even no search engine traffic at all.</p>
<p>Does that mean that big moves are too risky, or even not doable? Not at all. You just need deep pockets. If you lack a budget to feed the site with PPC or other bought traffic to compensate an estimated loss of organic traffic lasting at least a few weeks, but perhaps months, then don&#8217;t move. And when you move, then set up a professionally managed project, and hire experts for this task.</p>
<p>Here are some guidelines. I don&#8217;t provide a timeline, because that&#8217;s impossible without detailed knowledge of the individual circumstances. Adapt the procedure to fit your needs, nothing&#8217;s set in stone.
<ul>
<li>Set up the site on the new Web server (new.com). In robots.txt block everything exept a temporary page telling that this server is the new home of your site. Link to this page to get search engines familiar with the new server, but make sure there are no links to blocked content yet.</li>
<li>Create mapping tables &#8220;old URL to new URL&#8221; (respectively algos) to prepare the 301 redirects etcetera. You could consolidate multiple pages under one redirect target and so on, but you better wait with changes like that. Do them after the move. When you keep the old site&#8217;s structure on the new server, you make the job easier for search engines.</li>
<li>If you plan to do structural changes after the move, then develop the redirects in a way that you can easily change the redirect targets on the old site, and prepare the internal redirects on the new site as well. In any case, your redirect routines must be able to redirect or not depending on parameters like site area, user agent / requestor IP and such stuff, and you need a flexible control panel as well as URL specific crawler auditing on both servers.</li>
<li>On old.com develop a server sided procedure which can add links to the new location on every page on your old domain. Identify your URLs with the lowest crawling frequency. Work out a time table for the move which considers page importance (with regard search engine traffic), and crawl frequency.</li>
<li>Remove the <code>Disallow:</code> statements in the new server&#8217;s robots.txt. Create one or more XML sitemap(s) for the new server and make sure that you set crawl-priority and change-frequency accurately, last-modified gets populated with the scheduled begin of the move (IOW the day the first search engine crawler can access the sitemap). Feed the engines with sitemap files listing the important URLs first. Add sitemap-autodiscovery statements to robots.txt, and manually submit the sitemaps to Google and Yahoo.</li>
<li>Fire up the scripts creating visible &#8220;this page will move to [new location] soon&#8221; links on the old pages. Monitor the crawlers on the new server. Don&#8217;t worry about duplicate content issues in this phase, &#8220;move&#8221; in the anchor text is a magic word. Do nothing until the crawlers have fetched at least the first and second link level on the new server, as well as most of the important pages.</li>
<li>Briefly explain your redirect strategy in robots.txt comments on both servers. If you can, add obversely HTML comments to the HEAD section of all pages on the old server. You will cloak for a while, and things like that can help to pass reviews by humans which might get an alert from an algo or spam report. It&#8217;s more or less impossible to redirect human traffic in chunks, because that results in annoying surfing experiences, inconsistent database updates, and other disadvantages. Search engines aren&#8217;t cruel and understand that.</li>
<li>301 redirect all human traffic to the new server. Serve search engines the first chunk of redirecting pages. Start with a small chunk of not more than 1,000 pages or so, and bundle related pages to preserve most of the internal links within each chunk.</li>
<li>Closely monitor the crawling and indexing process of the first chunk, and don&#8217;t release the next one before it has (nearly) finished. Probably it&#8217;s necessary to handle each crawler individually.</li>
<li>Whilst you release chunk after chunk of redirects to the engines adjusting the intervals based on your experiences, contact all sites linking to you and ask for URL updates (bear in mind to delay these requests for inbound links pointing to URLs you&#8217;ll change after the move for other reasons). It helps when you offer an incentive, best let your marketing dept. handle this task (having a valid reason to get in touch with those Webmasters might open some opportunities).</li>
<li>Support the discovery crawling based on redirects and updated inbound links by releasing more and more XML sitemaps on the new server. Enabling sitemap based crawling should somewhat correlate to your release of redirect chunks. Both discovery crawling and submission based crawling share the bandwith respectively the amount of daily fetches the crawling engine has determined for your new server. Hence don&#8217;t disturb the balance by submitting sitemaps listing 200,000 unimportant 5th level URLs whilst a crawler processes a chunk of landing pages promoting your best selling products. You can steer sitemap autodiscovery depending on the user agent (for MSN and Ask which don&#8217;t offer submit forms) in your robots.txt, in combination with submissions to Google and Yahoo. Don&#8217;t forget to maintain (delete or update frequently) the sitemaps after the move.</li>
<li>Make sure you can control your redirects forever. Pay the hosting service and the registrar of the old site for the next ten years upfront. <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </li>
</ul>
<p>Of course there&#8217;s no such thing as a bullet-proof procedure to move large sites, but you can do a lot to make the move as smoothly as possible. </p>
<h4 id="302-found-elsewhere">302 - Found [Elsewhere]</h4>
<p><img src="http://sebastians-pamphlets.com/img/posts/302-found-elsewhere.png" width="150" height="233" alt="302 Found Elsewhere" title="302 Found Elsewhere" style="margin-left:3px;" align="right"  />The 302 redirect, like the 303/307 response code, is kinda <em>soft redirect</em>. Whilst a 301-redirect indicates a <em>hard redirect</em> by telling the user agent that a requested address is outdated (should be deleted) and the resource must be requested under another URL, 302 (303/307) redirects can be used with URLs which are valid, and should be kept by the requestor, but don&#8217;t deliver content <em>at the time of the request</em>. In theory, a 302&#8242;ing URL could redirect to another URL with each and every request, and even serve contents itself every now and then. </p>
<p>Whilst that&#8217;s no big deal with user agents used by humans (browsers, screen readers), search engines crawling and indexing contents by following paths to contents which must be accessible for human surfers consider soft redirects unreliable by design. What makes indexing soft redirets a royal PITA is the fact that most soft redirects actually are meant to notify a permanent move. 302 is the default response code for all redirects, setting the correct status code is not exactly popular in developer crowds, so that gazillions of 302 redirects are syntax errors which mimic 301 redirects. </p>
<p>Search engines have no other chance than requesting those wrongly redirecting URLs over and over to persistently check whether the soft redirect&#8217;s functionality sticks with the implied behavior of a permanent redirect. </p>
<p>Also, way back when search engines interpreted soft redirects according to the HTTP standards, it was possible to <a href="http://blog.searchenginewatch.com/blog/050801-130330">hijack foreign resources with a 302 redirect</a> and even <a href="http://blog.searchenginewatch.com/blog/050524-120912">meta refreshes</a>. That means that a strong (high PageRank) URL 302-redirecting to a weaker (lower PageRank) URL on another server got listed on the SERPs with the contents pulled from the weak page. Since Internet marketers are smart folks, this behavior enabled creative content delivery: of course only crawlers saw the redirect, humans got a nice sales pitch.</p>
<p>With regard to search engines, 302 redirects should be applied very carefully, because ignorant developers and, well, questionable intentions, have forced the engines to handle 302 redirects in a way that&#8217;s not exactly compliant to Web standards, but <a href="http://www.mattcutts.com/blog/seo-advice-discussing-302-redirects/">meant to be the best procedure to fit a searchers interests</a>. When you do cross-domain 302s, you can&#8217;t predict whether search engines pick the source, the target, or even a completely different but nice looking URL from the target domain on their SERPs. In most cases the target URL of 302-redirects gets indexed, but according to Murphy&#8217;s law and experience of life &#8220;99%&#8221; leaves enough room for serious messups.</p>
<p>Partly the common 302-confusion is based on the HTTP standard(s). With regard to SEO, response codes usable with GET and HEAD requests are more important, so I simplify things by ignoring issues with POST requests. Lets compare the definitions:</p>
<blockquote><table align="center">
<tr>
<th width="49%"><b><a href="http://www.w3.org/Protocols/HTTP/1.0/spec.html#Status-Codes">HTTP/1.0</a></b></td>
<th width="1%"></td>
<th width="49%"><b><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3">HTTP/1.1</a></b></td>
</tr>
<tr>
<td valign="top"><b style="font-size:110%;">302 Moved Temporarily</b></p>
<p>The requested resource resides temporarily under a different URL. Since the redirection may be altered on occasion, the client should continue to use the Request-URI for future requests.</p>
<p>The URL must be given by the Location field in the response. Unless it was a HEAD request, the Entity-Body of the response should contain a short note with a hyperlink to the new URI(s). </td>
<td valign="top"></td>
<td valign="top"><b style="font-size:110%;">302 Found</b></p>
<p>The requested resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.</p>
<p>The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s).</td>
</tr>
</table>
</blockquote>
<p>First, there&#8217;s a changed reason phrase for the 302 response code. &#8220;Moved Temporarily&#8221; became &#8220;Found&#8221; (&#8221;Found Elsewhere&#8221;), and a new response code 307 labelled &#8220;Temporary Redirect&#8221; was introduced (the other new response code <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4">303</a> &#8220;See Other&#8221; is for POST results redirecting to a resource which requires a GET request). </p>
<p>Creatively interpreted, this change could indicate that we should replace 302 redirects applied to temporarily moved URLs with 307 redirects, reserving the 302 response code for hiccups and redirects done by the Web server itself &#8211;without an explicit redirect statement in the server&#8217;s configuration (httpd.conf or .htaccess)&#8211;, for example in response to requests of maliciously shortened URIs (of course a 301 is the right answer in this case, but some servers use the &#8220;wrong&#8221; 302 response code by default to err on the side of caution until the Webmaster sets proper canonicalization redirects returning 301 response codes).</p>
<p>Strictly interpreted, this change tells us that the 302 response code must not be applied to moved URLs, regardless whether the move is really a temporary replacement (during maintenance windows, to point to mirrors of pages on overcrowded servers during traffic spikes, &#8230;) or even a permanent forwarding request where somebody didn&#8217;t bother sending a status line to qualify the location directive. As for maintenance, better use <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4">503</a> &#8220;Service Unavailable&#8221;!</p>
<p>Another important change is the addition of the non-cachable instruction in HTTP/1.1. Because the HTTP/1.0 standard didn&#8217;t explicitely state that the URL given in location must not be cached, some user agents did so, and the few Web developers actually reading the specs thought they&#8217;re allowed to simplify their various redirects (302&#8242;ing everything), because in the eyes of a developer nothing is really there to stay (SEOs, who handle URLs as assets, often don&#8217;t understand this philosophy, thus sadly act confrontational instead of educational).</p>
<p>Having said all that, is there still a valid use case for 302 redirects? Well, since 307 is an invalid response code with HTTP/1.0 requests, and crawlers still perform those, there&#8217;s no alternative to 302. Is that so? Not really, at least not when you&#8217;re dealing with overcautious search engine crawlers. Most HTTP/1.0 requests from search engines are faked, that means the crawler understands everything HTTP/1.1 but sends an HTTP/1.0 request header just in case the server runs since the Internet&#8217;s stone age without any upgrades. Yahoo&#8217;s Slurp for example does faked HTTP/1.0 requests in general, whilst you can trust Ms. Googlebot&#8217;s request headers. If Google&#8217;s crawler does an HTTP/1.0 request, that&#8217;s either testing the capabilities of a newly discovered server, or something went awfully wrong, usually on your side.</p>
<p>Google&#8217;s as well as Yahoo&#8217;s crawlers understand both the 302 and the 307 redirect (there&#8217;s no official statement from Yahoo though). But there are other Web robots out there (like link checkers of directories or similar bots send out by site owners to automatically remove invalid as well as redirecting links), some of them consisting of legacy code. Not to speak of ancient browsers in combination with Web servers which don&#8217;t add the hyperlink piece to 307 responses. So if you want to do everything the right way, you send 302 responses to HTTP/1.0 requestors &#8211;except when the user agent and the IP address identify a major search engine&#8217;s crawler&#8211;, and 307 responses to everything else &#8211;except when the HTTP/1.1 user agent lacks understanding of 307 response codes&#8211;. Ok, ok, ok &#8230; you&#8217;ll stick with the outdated 302 thingy. At least you won&#8217;t change old code just to make it more complex than necessary. With newish applications, which rely on state of the art technologies like AJAX anyway, you can quite safely assume that the user agents understand the 307 response, hence go for it and bury the wrecked 302, but submit only non-redirecting URLs to other places. </p>
<p>Here is how Google handles 302 redirects:<br />
<blockquote>[<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40193">Source</a> &#8230;] you shouldn&#8217;t use it to tell the Googlebot that a page or site has moved because Googlebot will continue to crawl and index the original location.</p></blockquote>
<p>Well, that&#8217;s not much info, and obviously a false statement. Actually, Google continues to <em>crawl</em> the redirecting URL, then <em>indexes</em> the source URL with the target&#8217;s content from redirects within a domain or subdomain only &#8211;but not always&#8211;, and mostly <em>indexes</em> the target URL and its content when a 302 redirect leaves the domain of the redirecting URL &#8211;if not any other URL redirecting to the same location or serving the same content looks prettier&#8211;. In most cases Google indexes the content served by the target URL, but in some cases all URL candidates involved in a redirect lose this game in favor of another URL Google has discovered on the target server (usually a short and pithy URL).</p>
<p>Like with 301 redirects, Yahoo &#8220;breaks the rules&#8221; with 302 redirects too:<br />
<blockquote>
<p>[<a href="http://help.yahoo.com/l/us/yahoo/search/webcrawler/slurp-11.html">Source</a> &#8230;] When one web page redirects to another web page, Yahoo! Web Search sometimes indexes the page content under the URL of the entry or &#8220;source&#8221; page, and sometimes index it under the URL of the final, destination, or &#8220;target&#8221; page. [&#8230;]</p>
<p>When a page in one domain redirects to a page in another domain, Yahoo! records the &#8220;target&#8221; URL. [&#8230;]</p>
<p>When a page in a domain presents a temporary redirect to another page in the same domain, Yahoo! indexes the &#8220;source&#8221; URL.</p>
<p>Yahoo! Web Search indexes URLs that redirect according to the general guidelines outlined above with the exception of special cases that might be read and indexed differently. [&#8230;]</p>
</blockquote>
<p>One of these cases where Yahoo handles redirects &#8220;differently&#8221; (meaning according to the HTTP standards) is a soft redirect from the root index page to a deep page. Like with a 301 redirect, Yahoo indexes the home page URL with the contents served by the redirect&#8217;s target. </p>
<p>You see that there are not that much advantages of 302 redirects pointing to other servers. Those redirects are most likely understood as somwhat permanent redirects, what means that the engines most probably crawl the redirecting URLs in a lower crawl frequency than 307 redirects. </p>
<p>If you have URLs which change their contents quite frequently by redirecting to different resources (from the same domain or on another server), and you want search engines to index and rank those timely contents, then consider the hassles of IP/UA based response codes depending on the protocol version. Also, feed those URLs with as much links as you can, and list them in an <a href="http://sebastians-pamphlets.com/links/categories/?cat=xml-sitemaps">XML sitemap</a> with a <a href="http://www.sitemaps.org/protocol.php#prioritydef">high priority value</a>, a <a href="http://www.sitemaps.org/protocol.php#lastmoddef">last modified timestamp</a> like <em>request timestamp minus a few seconds</em>, and an &#8220;always&#8221;, &#8220;hourly&#8221; or &#8220;daily&#8221; <a href="http://www.sitemaps.org/protocol.php#changefreqdef">change frequency</a> tag. Do that even when you for whatever reasons have no XML-sitemap at all. There&#8217;s no better procedure to pass such special instructions to crawlers, even an XML sitemap listing only the ever changing URLs should do the trick.</p>
<p>If you promote your top level page but pull the contents from deep pages or scripts, then a 302 meant as 307 from the root to the output device is a common way to avoid duplicate content issues while serving contents depending on other request signals than the URI alone (cookies, geo targeting, referrer analysis, &#8230;). However, that&#8217;s a case where you can avoid the redirect. Duplicating one deep page&#8217;s content on root level is a non-issue, a superfluous redirect is an issue with regard to performance at least, and it sometimes slows down crawling and indexing. When you output different contents depending on user specific parameters, treating crawlers as users is easy to accomplish. I&#8217;d just make the root index default document a script outputting the former redirect&#8217;s target. That&#8217;s a simple solution without redirecting anyone (which sometimes directly feeds the top level URL with PageRank from user links to their individual &#8220;home pages&#8221;).</p>
<h4 id="307-temporary-redirect">307 - Temporary Redirect</h4>
<p><img src="http://sebastians-pamphlets.com/img/posts/307-temporary-redirect.png" width="200" height="135" alt="307 Temporary Redirect" title="307 Temporary Redirect" style="margin-left:3px;" align="right"  />Well, since the 307 redirect is the 302&#8217;s official successor, I&#8217;ve told you nearly everything about it in the 302 section. Here is the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8">HTTP/1.1 definition</a>:<br />
<blockquote><b>307 Temporary Redirect</b></p>
<p>The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.</p>
<p>The temporary URI SHOULD be given by the Location field in the response. Unless the request method was HEAD, the entity of the response SHOULD contain a short hypertext note with a hyperlink to the new URI(s), since many pre-HTTP/1.1 user agents do not understand the 307 status. Therefore, the note SHOULD contain the information necessary for a user to repeat the original request on the new URI.</p></blockquote>
<p>The 307 redirect was introduced with HTTP/1.1, hence some user agents doing HTTP/1.0 requests do not understand it. Some! Actually, many user agents fake the protocol version in order to avoid conflicts with older Web servers. Search engines like Yahoo for example perform faked HTTP/1.0 requests in general, although their crawlers do talk HTTP/1.1. If you make use of the <a href="http://www.feedburner.com/fb/a/help/wordpress_quickstart">feedburner plugin</a> to redirect your WordPress feeds to feedburner.com/yourfeed, respectively feeds.yourdomain.com resolving to feedburner.com/yourfeed, you&#8217;ll notice that Yahoo bots do follow 307 redirects, although Yahoo&#8217;s official documentation does not even mention the 307 response code. </p>
<p>Google states how they handle 307 redirects as follows:<br />
<blockquote>[<a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40205">Source</a> &#8230;] The server is currently responding to the request with a page from a different location, but the requestor should continue to use the original location for future requests. This code is similar to a <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40151">301</a> in that for a GET or HEAD request, it automatically forwards the requestor to a different location, but you shouldn&#8217;t use it to tell the Googlebot that a page or site has moved because Googlebot will continue to crawl and index the original location.</p></blockquote>
<p>Well, a summary of the HTTP standard plus a quote from the <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=40193">302 page</a> is not exactly considered a comprehensive help topic. However, checked with the feedburner example, Google understands 307s as well.</p>
<p>A 307 should be used when a particular URL for whatever reason must point to an external resource. When you for example burn your feeds, redirecting your blog software&#8217;s feed URLs with a 307 response code to &#8220;your&#8221; feed at feedburner.com or another service is the way to go. In this case it plays no role that many HTTP/1.0 user agents don&#8217;t know shit about the 307 response code, because all software dealing with RSS feeds can understand and handle HTTP/1.1 response codes, or at least can interpret the class 3xx and request the feed from the URI provided in the header&#8217;s location field. More important, because with a 307 redirect each revisit has to start at the redirecting URL to fetch the destination URI, you can move your burned feed to another service, or serve it yourself, whenever you choose to do so, without dealing with longtime cache issues. </p>
<p>302 temporary redirects might result in cached addresses from the location&#8217;s URL due to an unprecise specification in the HTTP/1.0 protocol, but that shouldn&#8217;t happen with HTTP/1.1 response codes which, in the 3xx class, all clearly tell what&#8217;s cachable and what not. </p>
<p>When your site&#8217;s logs show a tiny amount of <em>actual</em> HTTP/1.0 requests (eliminate crawlers of major search engines for this report), you really should do 307 redirects instead of wrecked 302s. Of course, avoiding redirects where possible is always the better choice, and don&#8217;t apply 307 redirects to moved URLs.</p>
<h3 id="redirect-recap">Recap</h3>
<p><img src="http://sebastians-pamphlets.com/img/posts/redirect-301-302-307-recap.png" width="150" height="294" alt="301-302-307-redirect-recap" title="Recap, too short, better read the book, err post" style="margin-left:3px;" align="right"  />Here are the bold sentences again. Hop to the sections via the <a href="http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/#redirect-jump-station">table of contents</a>.</p>
<ul>
<li>Avoid redirects where you can. URLs, especially linked URLs, are assets. Often you can include other contents instead of performing a redirect to another resource. Also, there are hyperlinks.</li>
<li>Search engines process HTTP redirects (301, 302 and 307) as well as meta refreshes. If you can, always go for the cleaner server sided redirect.</li>
<li>Always redirect to the final destination to avoid useless hops which kill your search engine traffic. With each and every revamp that comes with URL changes check for incoming redirects and make sure that you eliminate unnecessary hops.</li>
<li>You must maintain your redirects forever, and you must not remove (permanent) redirects. Document all redirects, especially when you do redirects both in the server configuration as well as in scripts.</li>
<li>Check your logs for redirects done by the Web server itself and unusual 404 errors. Vicious Web services like Yahoo or MSN screw your URLs to get you in duplicate content troubles with Google.</li>
<li>Don&#8217;t track links with redirecting scripts. Avoid redirect scripts in favor of link attributes. Don&#8217;t hoard PageRank by routing outgoing links via an uncrawlable redirect script, don&#8217;t buy too much of the search engine FUD, and don&#8217;t implement crappy advice from Webmaster hangouts.</li>
<li>Clever redirects are your friend when you handle incoming and outgoing affiliate links. Smart IP/UA based URL cloaking with permanent redirects makes you independent from search engine canonicalization routines which can fail, and improves your overall search engine visibility.</li>
<li>Do not output anything before an HTTP redirect, and terminate the script after the last header statement.</li>
<li>For each server sided redirect, send an HTTP status line with a well choosen response code, and an absolute (fully qualified) URL in the location field. Consider tagging the redirecting script in the header (X-Redirect-Src).</li>
<li>Put any redirect logic at the very top of your scripts. Encapsulate redirect routines. Performance is not everything, transparency is important when the shit hits the fan.</li>
<li>Test all your redirects with server header checkers for the right response code and a working location. If you forget an HTTP status line, you get a 302 redirect regarless your intention.</li>
<li>With canonicalization redirects use <em>not equal</em> conditions to cover everything. Most .htaccess code posted on Webmaster boards, supposed to fix for example www vs. non-www issues, is unusable. If you reply &#8220;thanks&#8221; to such a post with your URL in the signature, you invite saboteurs to make use of the exploits.</li>
<li>Use only 301 redirects to handle permanently moved URLs and canonicalization. Use 301 redirects only for persistent decisions. In other words, don&#8217;t blindly 301 everything.</li>
<li>Don&#8217;t redirect too many URLs simultaneous, move large amounts of pages in smaller chunks.</li>
<li>99% of all 302 redirects are either syntax errors or semantically crap, but there are still some use cases for search engine friendly 302 redirects. &#8220;Moved URLs&#8221; is not on that list. </li>
<li>The 307 redirect can replace most wrecked 302 redirects, at least in current environments.</li>
<li>Search engines do not handle redirects according to the HTTP specs any more. At least not when a redirect points to an external resource.</li>
</ul>
<p>I&#8217;ve asked Google in their <a href="http://groups.google.com/group/Google_Webmaster_Help-Indexing/browse_thread/thread/72231e3bdd7a31f8/f65ee284f4fd4129">popular picks campaign</a> for a comprehensive write-up on redirects (what is part of the ongoing help system revamp anyway, but I&#8217;m either greedy or not patient enough). If my question gets picked, I&#8217;ll update this post. </p>
<p>Did I forget anything else? If so, please submit a comment. <img src='http://sebastians-pamphlets.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/", "style": "big", "title": "The anatomy of a server sided redirect: 301, 302 and 307 illuminated SEO wise" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/the-anatomy-of-http-redirects-301-302-307/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Shit happens, your redirects hit the fan!</title>
		<link>http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/</link>
		<comments>http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/#comments</comments>
		<pubDate>Wed, 26 Sep 2007 20:35:27 +0000</pubDate>
		<dc:creator>Sebastian</dc:creator>
		
		<category><![CDATA[404grabber]]></category>

		<category><![CDATA[Redirects]]></category>

		<category><![CDATA[Web development]]></category>

		<category><![CDATA[.htaccess]]></category>

		<category><![CDATA[SEO]]></category>

		<category><![CDATA[Webmaster Central]]></category>

		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/</guid>
		<description><![CDATA[
Although robust search engine crawlers are rather fault-tolerant creatures, there is an often overlooked but quite safe procedure to piss off the spiders. Playing redirect ping pong mostly results in unindexed contents. Google reports chained redirects under the initially requested URL as URLs not followed due to redirect errors, and recommends:
Minimize the number of redirects [...]]]></description>
			<content:encoded><![CDATA[
<p><img src="http://sebastians-pamphlets.com/img/posts/confuse-the-hell-out-of-the-spiders.png" border="0" width="200" height="168" align="right" alt="confused spider" title="Don't confuse the spiders! They might puke ..."  />Although robust search engine crawlers are rather fault-tolerant creatures, there is an often overlooked but quite safe procedure to piss off the spiders. Playing redirect ping pong mostly results in unindexed contents. Google reports chained redirects under the initially requested URL as <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=35156">URLs not followed</a> due to <a href="http://www.google.com/support/webmasters/bin/answer.py?answer=35157">redirect errors</a>, and recommends:<br />
<blockquote>Minimize the number of redirects needed to follow a link from one page to another.</p></blockquote>
<p>The same goes for other search engines, they can&#8217;t handle longish chains of redirecting URLs. In other words: all search engines consider URLs involved in longish redirect chains unreliable, not trustworthy, low quality &#8230;</p>
<p>What&#8217;s that to you? Well, you might play redirect ping pong with search engine crawlers unknowingly. If you&#8217;ve ever redesigned a site, chances are you&#8217;ve build chained redirects. In most cases those chains aren&#8217;t too complex, but it&#8217;s worth checking. Bear in mind that Apache, .htaccess, scripts or CMS software and whatnot can perform redirects, often without notice and undetectable with a browser. </p>
<p>I made up this example, but I&#8217;ve seen worse redirect chains. Here is the transcript of Ms. Googlebot&#8217;s chat with your Web server:<br />
<img src="http://sebastians-pamphlets.com/img/posts/redirect-chains-crawler-server-dialog.png" border="0" width="498" height="277" align="center" alt="crappy redirect chain" title="Avoid chained redirects!"  /></p>
<p class="question"><span style="text-transform:uppercase; text-decoration:overline;">Googlebot:</span> Now that&#8217;s a nice link I&#8217;ve discovered on this old and trusted page. I can&#8217;t wait to fetch it. Hey port 80 at yourstuff.com, would you please be so kind to serve me <code>/some-page</code>?</p>
<p class="answer"><span style="text-transform:uppercase; text-decoration:overline; font-weight:bold;">.htaccess:</span> Oh silly Googlebot, don&#8217;t you read <a href="http://www.mattcutts.com/blog/seo-advice-url-canonicalization/">Matt&#8217;s blog</a>? He told me that a 301 redirect is the canonical answer when someone requests my stuff without the www-prefix. I didn&#8217;t bother to lookup the resource you&#8217;ve asked for, and why should I since your request is wrong, wrong, wrong! Here is the canonical URL: <code>301-Moved permanently, Location: http://www.yourstuff.com/some-page</code>.</p>
<p class="question"  id="incomplete-uri"><span style="text-transform:uppercase; text-decoration:overline;">Googlebot:</span> Dear Web server, of course that&#8217;s the best thing to do. I apologize for my silly request, but please note that I&#8217;m following a link where the Webmaster of the authority site forgot the dup-dup-dup stuff in the HREF attribute&#8217;s value. Can you please serve me <code>/some-page</code> now?</p>
<p class="answer"><span style="text-transform:uppercase; text-decoration:overline; font-weight:bold;">Apache:</span> Doh! Why does this silly bot bother me with an incomplete URI? Since <code>/some-page</code> is not an existing file, probably it&#8217;s a directory and a brain dead Webmaster forgot the trailing slash. Lets see &#8230; yep, that&#8217;s it, and it has even a default document <code>index.php</code>. Dear Ms. Googlebot, here is the correct URL: <code>302-Found elsewhere, Location: http://www.yourstuff.com/some-page/index.php</code>.</p>
<p><small>[Most servers will respond with <code>301-Moved permanently, Location: http://www.yourstuff.com/some-page/</code>, but however the server is configured, it will be a redirect.]</small></p>
<p class="question"><span style="text-transform:uppercase; text-decoration:overline;">Googlebot:</span> Oh I see, I&#8217;ve got a really malformed URI. Sorry for bothering you again, could you please deliver the content of <code>http://www.yourstuff.com/some-page/index.php</code>? Thanks in advance!</p>
<p class="answer"><span style="text-transform:uppercase; text-decoration:overline; font-weight:bold;">/some-page/index.php:</span> Uuaahhh &#8230; who&#8217;s knocking? I slept sooo long &#8230; not fully awake &#8230; please be patient while Apache hands me over to the PHP parser. Actually, I&#8217;m totally outdated because my Webmaster discovered some blogging software and moved my contents to a WordPress database. Please wait. Where is the darn post-it with the new address? Ahh, just found it under my pillow. Please don&#8217;t disturb me again, bye bye, and here you go: <code>301-Moved permanantly, Location: http://www.yourstuff.com/blog/some-post/</code>.</p>
<p class="question"><span style="text-transform:uppercase; text-decoration:overline;">Googlebot:</span> You&#8217;re kidding! Why didn&#8217;t you give me this URI in the first place? Never mind, I want <code>http://www.yourstuff.com/blog/some-post/</code> now.  </p>
<p class="answer"><span style="text-transform:uppercase; text-decoration:overline; font-weight:bold;">Hack in /blog/index.php:</span> Oh my god, another bot following outdated links. My Webmaster is clever, he read somewhere that category names in URLs boost search engine rankings and changed the permalink structure to category/postname. Wait a moment, I&#8217;m looking up the category for this post, be right back. Hmmm, this category name is not exactly a money term &#8230; the heck with it! Here is the keyword stuffed URL I just made for you: <code>301-Moved permanantly, Location: http://www.yourstuff.com/blog/cat/some-post/</code>.</p>
<p class="question"><span style="text-transform:uppercase; text-decoration:overline;">Googlebot:</span> Four crappy redirects in a row, what a bunch of bull! This is my ultimately last try: gimme <code>http://www.yourstuff.com/blog/cat/some-post/</code>!</p>
<p class="answer"><span style="text-transform:uppercase; text-decoration:overline; font-weight:bold;">WordPress:</span> See, that didn&#8217;t hurt, did it? Here you are: <code>200-OK, the content</code></p>
<p class="question"><span style="text-transform:uppercase; text-decoration:overline;">Googlebot:</span> Here&#8217;s your shabby page. Don&#8217;t send me to this assclowns again! I&#8217;ve better things to do than running five times to this misconfigured server only to fetch a keyword laden sales pitch with 34 grammar errors, 67 typos, and a ton of affiliate links. Grrrr! </p>
<p class="answer"><span style="text-transform:uppercase; text-decoration:overline; font-weight:bold;">Crawl scheduler:</span> Sorry dear. I can&#8217;t blacklist them for stuff like that, but I&#8217;ve set the crawl frequency for yourstuff.com to once a year, and I&#8217;ve red-flagged the document ID so that the indexer can downrank it accordingly.</p>
<p>Do you really want to treat Ms. Googlebot so badly? Not to speak of the minus points you gain for playing redirect ping pong with a search engine. Maybe most search engines index a page served after four redirects, but I won&#8217;t rely on such a redirect chain. It&#8217;s quite easy to shorten it. Just delete outdated stuff so that all requests run into a 404-Not found, then write up a list in a format like<br />
<table align="center" style="margin-left:20px; margin-bottom:15px;" cellpadding="5" cellspacing="5">
<tr>
<td><code>Old URI 1</code></td>
<td>Delimiter</td>
<td><code>New URI 1</code></td>
<td>\n</td>
</tr>
<tr>
<td><code>Old URI 2</td>
<td>Delimiter</td>
<td><code>New URI 2</code></td>
<td>\n</td>
</tr>
<tr>
<td>&nbsp;&nbsp;&#8230;</td>
<td>Delimiter</td>
<td>&nbsp;&nbsp;&#8230;</td>
<td>\n</td>
</tr>
</table>
<p><span style="margin-top:30px;"></span>and write a simple redirect script which reads this file and performs a 301 redirect to <code>New URI</code> when <code>REQUEST_URI == Old URI</code>. If <code>REQUEST_URI</code> doesn&#8217;t match any entry, then send a 404 header and include your actual error page. If you need to change the final URLs later on, you can easily do that in the text file&#8217;s right column with search and replace.</p>
<p>Next point the <code>ErrorDocument 404</code> directive in your root&#8217;s .htaccess file to this script. Done. Not looking at possible www/non-www canonicalization redirects, you&#8217;ve shortened the number of redirects to one, regardless how often you&#8217;ve moved your pages. Don&#8217;t forget to add all outdated URLs to the list when you redesign your stuff again, and cover common 3rd party sins like truncating trailing slashes too. The flat file from the example above would look like:</p>
<table  align="center" style="margin-left:20px; margin-bottom:15px;"  cellpadding="5" cellspacing="5">
<tr>
<td><code>/some-page</code></td>
<td>Delimiter</td>
<td><code>/blog/cat/some-post/</code></td>
<td>\n</td>
</tr>
<tr>
<td><code>/some-page/</code></td>
<td>Delimiter</td>
<td><code>/blog/cat/some-post/</code></td>
<td>\n</td>
</tr>
<tr>
<td><code>/some-page/index.php</code></td>
<td>Delimiter</td>
<td><code>/blog/cat/some-post/</code></td>
<td>\n</td>
</tr>
<tr>
<td><code>/blog/some-post</code></td>
<td>Delimiter</td>
<td><code>/blog/cat/some-post/</code></td>
<td>\n</td>
</tr>
<tr>
<td><code>/blog/some-post/</code></td>
<td>Delimiter</td>
<td><code>/blog/cat/some-post/</code></td>
<td>\n</td>
</tr>
<tr>
<td>&nbsp;&nbsp;&#8230;</td>
<td>Delimiter</td>
<td>&nbsp;&nbsp;&#8230;</td>
<td>\n</td>
</tr>
</table>
<p><span style="margin-top:30px;"></span>With a large site consider a database table, processing huge flat files with every 404 error can come with disadvantages. Also, if you&#8217;ve patterns like <code>/blog/post-name/ ==&gt; /blog/cat/post-name/</code> then don&#8217;t generate and process longish mapping tables but cover these redirects algorithmically.</p>
<p>To gather URLs worth a 301 redirect use these sources:</p>
<ul>
<li>Your server logs.</li>
<li>404/301/302/&#8230; reports from your server stats.</li>
<li>Google&#8217;s <a href="https://www.google.com/webmasters/tools/webcrawlerrors?siteUrl=http://example.com/&#038;hl=en" rel="example nofollow">Web crawl error reports</a>.</li>
<li>Tools like <a href="http://home.snafu.de/tilman/xenulink.html">XENU&#8217;s Link Sleuth</a> which crawl your site and output broken links as well as all sorts of redirects, and can even check your complete Web space for orphans.</li>
<li>Sitemaps of outdated structures/site areas.</li>
<li><a href="http://www.seoconsultants.com/tools/headers/">Server header checkers</a> which follow all redirects to the final destination.</li>
<li>&#8230;</li>
</ul>
<p><b>Disclaimer:</b> If you suffer from IIS/ASP, free hosts, restrictive hosts like Yahoo or other serious maladies, this post is not for you.</p>
<p><b>I&#8217;m curious, <strike>does</strike> did your site play redirect ping pong with search engine crawlers?</b> </p>
<hr />Copyright &copy; 2010 <strong><a href="http://sebastians-pamphlets.com/">Sebastian`s Pamphlets</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator/feed reader, the site you are looking at is guilty of copyright infringement and will be put down immediately. Please contact sebastians-pamphlets.com so we can take legal action immediately.<br /><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span><div class="topsy_widget_data topsy_theme_light-green" style="float: right;margin-left: 0.75em;"><!-- { "url": "http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/", "style": "big", "title": "Shit happens, your redirects hit the fan!" } --></div>
]]></content:encoded>
			<wfw:commentRss>http://sebastians-pamphlets.com/how-to-avoid-troubles-caused-by-chained-redirects/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
