I'm trying to setup client-side redirects instead of server-side redirects. Since Varnish is being used for caching, I would like that to remain; so the request should not get to Drupal, Varnish should handle the redirect. Ultimately, using session cookies, I'm trying to have the value for source/referrer path available at the landing page (because redirects clear the original referrer headers).

In Drupal 7, within a custom module, I'm using hook_redirect_alter() to stop the redirect process, then print out javascript to the page to do the redirect. My question is, what is the Drupal way of adding the below print statement to the page within this hook?

 * Implements hook_redirect_alter().
function mymodule_redirect_alter($redirect) {
    <script src="sites/all/modules/contrib/jquery_update/replace/jquery/1.10/jquery.min.js?v=1.10.2"></script>
    <script src="sites/all/modules/contrib/jquery_update/replace/ui/external/jquery.cookie.js"></script>
      $(function() {
        var source = $(location).attr("pathname");
        var source = source.slice(1);
        $.cookie("source", source);
        window.location.replace("' . $redirect->redirect .'");
      <a href="/' . $redirect->redirect . '">Javascript is disabled. Click here to continue</a>

  // This kills sever-side redirect

1 Answer 1


Since you cannot specify a 301 redirect in javascript, here is what I did all within hook_redirect_alter() :

function mymodule_redirect_alter($redirect) {
  // If checkbox is set then use URL parameter for redirect, otherwise ignore everything
  if (variable_get('my_checkbox', '') == '1') {
    $params = drupal_get_query_parameters();
    $my_parameter = variable_get('my_parameter', '');

    // Append redirect values seperated by commas if the specified parameter exists    
    if (!empty($params[$my_parameter])) {
      $refs = $params[$my_parameter] . ',' . $redirect->source;
    // Otherwise add souce as the value of the parameter
    else {
      $refs = $redirect->source;

    // Create parameters to append to URL
    $params = array('query' => array($my_parameter => $refs));

    // Do the actual redirect with this new parameter
    drupal_goto($redirect->redirect, $params);

    // This kills sever-side redirect

So the URL mysite.com/original_page will be redirected to a page with URL mysite.com/mypage?redirect=original_page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.