Short URL links with Drupal 6 on ao2.it
Added short URL links to ao2.it, you will find one at the end of each node content.
I decided to use the simple approach of nids as unique identifiers, together with Apache URL rewriting as seen in URL Shorteners Must Die.
Apply this patch to Drupal .htaccess to recognize short URLs in the form http://example.com/123
:
Redirect URLs in the form
http://example.com/123
to
http://example.com/node/123
from here on Drupal will take care of any other URL aliasing.
Signed-off-by: Antonio Ospite <ospite@studenti.unina.it>
---
.htaccess | 3 +++
1 file changed, 3 insertions(+)
Index: drupal/.htaccess
===================================================================
--- drupal.orig/.htaccess
+++ drupal/.htaccess
@@ -106,6 +106,9 @@
# uncomment the following line:
# RewriteBase /
+ # Allow short URLs of the form http://example.com/123
+ RewriteRule ^(\d+)$ index.php?q=node/$1 [L,QSA]
+
# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Then from THEME_preprocess_node()
(change THEME to match your actual theme name) in template.php call the function below to set a new variable that can be used in other templates:
/**
* Add a new shortlink variable
*/
function THEME_preprocess_node_add_shortlink(&$vars) {
$node = $vars['node'];
$options = array(
'language' => '',
'alias' => TRUE,
'absolute' => TRUE,
);
$shortlink = url($node->nid, $options);
/* add also the info to the header when viewing a node page */
if (arg(0) == 'node') {
drupal_set_html_head('<link rel="shortlink" href="'. $shortlink .'" />');
drupal_set_header('Link: <' . $shortlink . '>; rel=shortlink');
}
$options = array(
'language' => '',
'attributes' => array(
'title' => $node->title,
'rel' => 'shortlink nofollow',
),
);
$vars['shortlink'] = l($shortlink, $shortlink, $options);
}
The code above adds support for the shortlink relation specification, and takes care to add the nofollow relation to the short duplicate link for the content, which shouldn't hurt.
The new variable for the actual link can be used wherever the short URL link is wanted to show up:
print '<div class="shortlink">'.t('Short link'). ': ' . $shortlink . '</div>';
A problem with this approach could be the multiple redirects performed before actually serving the content:
/[nid] -> /node/[nid] -> content at Pathauto generated alias
I haven't checked if caching mechanisms at the web server can help with that, anyone?
An alternative, more complete solution, would have been to use the Short URL and Shorten Drupal modules; overkill for my use case.
I still have to find a way to add support for short URLs to AddToAny without patching it.