custom_url_rewrite

Хочешь помочь с переводом? Это очень просто и быстро. Лишь зарегистрируйся, и можешь тут же начать переводить.

developer/hooks/core.php, строка 1572

Версии
5
custom_url_rewrite($op, $result, $path)

custom_url_rewrite не является хуком. Это функция, которую вы можете добавить в settings.php, для управления и переадресации путей в Друпале.

Параметры

$op Может быть 'alias' или 'source'. Для 'alias' — должен быть возвращен синоним пути. Для 'source' — внутренний путь Друпала. 'source' вызывается перед загрузкой модулей и инициализацией системы меню и $_GET['q'] будет заполнено значением, которое возвращает эта функция.

$result Для 'alias' — синоним пути, загруженный из базы данных. Для 'source' — внутренний путь Друпала, соответствующий адресу текущей страницы (синониму). Если в базе не найдется синонима к данному пути, значение $result будет таким же как и $path для обоих операций.

$path Путь, для которого нужно найти синоним или соответствие.

Возвращаемое значение

Измененный путь (даже если измеений не было, путь должен быть возвращен).

Связанные темы

▾ 2 функции вызывают custom_url_rewrite()

drupal_get_normal_path in includes/path.inc
Получает синоним пути, возвращает системный путь, для этого синонима.
drupal_get_path_alias in includes/path.inc
Возвращает синоним, к внутреннему пути друпала.

Код

<?php
function custom_url_rewrite($op, $result, $path) {
  global $user;
  if ($op == 'alias') {
    // Overwrite a menu path already defined, with this code, if the user
    // goes to 'tracker', the page 'views/tracker' will be displayed instead
    // without any redirection. To achieve this, only the op source act is a
    // must, this is optional.
    if ($path == 'views/tracker') {
      return 'tracker';
    }
    // Change all 'node' to 'article'.
    if (preg_match('|^node/(.*)|', $path, $matches)) {
      return 'article'. $matches[1];
    }
    // Create a path called 'e' which lands the user on her edit page.
    if ($path == 'user/'. $user->uid .'/edit') {
      return 'e';
    }
  }
  if ($op == 'source') {
    if ($path == 'tracker') {
      // Change 'tracker' to 'views/tracker' when a request lands.
      return 'views/tracker';
    }
    // Change all 'node' to 'article'.
    if (preg_match('|^article(/.*)|', $path, $matches)) {
      return 'node'. $matches[1];
    }
    // Create a path called 'e' which lands the user on her edit page.
    if ($path == 'e') {
      return 'user/'. $user->uid .'/edit';
    }
  }
  // Do not forget to return $result!
  return $result;
}
?>

Пользовательские комментарии

The following tip can be used in multiple scenarios (being anywhere you need custom URL rewriting and want to do this without .htaccess), but I'll illustrate it for two specific purposes.

  • At our company all urls beginning with /admin are blocked from outside by a firewall for content security reasons. This sucks, because Drupal administration is done on pages with a /admin url. So we need to find a way to rewrite all of the urls to something like /config (or something else).
  • If someone knows your site is on Drupal, this gives him some knowledge on how the site is structured. For example does he know that all administration is done on /admin. To make it harder to guess this url, we want to rename it.

Both of these cases can be tackled by one hook (custom_url_rewrite) in Drupal that has to be specified in the settings.php file. You can find a descent explanation of how this hook works in the Drupal API.

In the following example I rewrite all admin urls to config (and vice versa).

function custom_url_rewrite($op, $result, $path) {
  if ($op == 'alias') {
    if (preg_match('|^admin(/{0,1}.*)|', $path, $matches)) {
      return 'config'. $matches[1];
    }
  }
 
  if ($op == 'source') {
    if (preg_match('|^config(/{0,1}.*)|', $path, $matches)) {
      return 'admin'. $matches[1];
    }
  }
 
  return $result;
 
}
Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Вход в систему