Even if you disable Redirect Customer to Account Dashboard after Logging, in the Admin Panel in System > Configuration > Customer Configuration, in many cases referer is not defined / kept when coming from outside the store to a login protected page.
Only the login link on the page passes referer properly base64 encoded by Magento (check the login URL).
Also, HTTP_REFERER can't be used as it gets lost on the login redirect (anyway it would need further processing to make it encoded).
In _loginPostRedirect() function from Magento core AccountController.php you can find how it works:
$referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME);
if ($referer) {
// Rebuild referer URL to handle the case when SID was changed
$referer = Mage::getModel('core/url')
->getRebuiltUrl(Mage::helper('core')->urlDecode($referer));
You can see that referer should be passed as a parameter and then it gets decoded by urlDecode().
One solution would be to modify the template file header.phtml and retain the original URL in a session variable, then overwrite the _loginPostRedirect() function to setBeforeAuthUrl() to it.
You can find a working solution which I've tested here: http://www.mihaimatei.com/redirect-previous-page-login-magento/