Руководство:Короткий URL-адрес

From mediawiki.org
This page is a translated version of the page Manual:Short URL and the translation is 51% complete.
Эта статья посвящена структуре URL-адресов. Для создание коротких URL-адресов статей смотрите Расширение:Короткие ссылки (ShortUrl) Для создание коротких URL-адресов статей смотрите Расширение:UrlShortener

Использование короткого веб-адреса, скрывающего сложный программный код, поможет посетителям вашего сайта легко запомнить принцип построения ссылки на нужную страницу. Во избежании проблем в будущем, рекомендуется настроить короткий веб-адрес вашего сайта в самом начале работы.

Введение

Цели

Путь установки MediaWiki по умолчанию выглядит так:

/var/www/html/mediawiki (установка с правами администратора)
/home/johndoe/public_html/mediawiki (при использовании виртуального хостинга)

Также, предполагается, что веб-адрес MediaWiki выглядит так:

https://example.org/w/index.php/Page_title (текущая версия MediaWiki без поддержки CGI)
https://example.org/w/index.php?title=Page_title (текущая версия MediaWiki с поддержкой CGI)

Используя методы, описанные ниже, длинный веб-адрес может быть преобразован в короткий, такой как эти:

https://example.org/wiki/Page_title Это наиболее распространённая конфигурация, такая же как в Википедии, однако она не является конфигурацией по умолчанию, поскольку требует изменений на стороне сервера
https://example.org/view/Page_title
https://wiki.example.org/view/Page_title
https://example.org/Page_title
https://wiki.example.org/Page_title

Some people do not recommend the last two configurations: see Manual:Wiki in site root directory for potential problems and solutions.

Преимущества и недостатки

  • Преимущества: Короткие URL скрывают от конечного пользователя некоторые технические детали, по желанию владельца сайта. Среди прочего, это означает, что ссылки могут оставаться неизменными при основательных программных изменениях. (Читай выше про выбор между стандартной структурой ссылок с CGI и без.) Они также облегчают чтение, запоминание и манипуляции с ссылками для посетителей. Additionally, short URLs offer an advantage over the default URLs for w:Search engine optimization, as URLs containing ? can be treated less favorably by search engines when calculating page rank.
  • Недостатки: Требует настройки, поэтому, в зависимости от среды хостинга, который Вы используете, может вызывать трудности. Однако, большинство популярных веб-серверов могут быть настроены на использование коротких URL-адресов, в особенности платные веб-хостинги. Любой хост, который не предоставляет такой возможности - не стоит Ваших денег.

Руководство

Наше официальное руководство по настройки коротких URL-адресов для различных веб-серверов. Выберите вашу конфигурацию веб-сервера из этого списка. Если Вы не знаете, какое программное обеспечение используется на Вашем сервере, то это, скорее всего, Apache.

Другие методы: мини-руководства

Эти руководства старые и являются почти полностью плохими советами. В конечном итоге они будут удалены один за другим, поскольку наши официальные руководства, приведенные выше, созданы для разных веб-серверов.

Любой желающий может создать страницу с практическим решением и перечислить его ниже. Пожалуйста, используйте простое и понятное всем название Вашего руководства! When each unique solution has its own page, readers can skip complexity they do not want. Keep it simple, readable, short, with a separate page per separate solution.

To help others find out which Short URL methods really work, after trying each method please edit the page and increase the "worked" or "didn't_work" numbers for that guide and make a brief (or long, your choice) description on what went wrong by clicking the link on your number.

Адреса в виде - example.com/wiki/Название_страницы

Actions such as edit, view history, etc. will still have index.php unless $wgActionPaths are defined.

Администраторский доступ Для использования этих методов необходимы права администратора. If you are on a shared host, you most likely don't. Если вы размещаете ваш проект на виртуальном хостинге, используйте руководства, для которых не требуются права администратора. You can jump directly to the MediaWiki ShortURL Builder tool and follow the on-screen instructions. Select "I don't have root access" after entering your wiki's URL.

(for Apache guidance, see the link in the Guides section).

Адреса в виде - example.com/Название_страницы

Some people do not recommend this configuration. See Manual:Wiki in site root directory for potential problems and solutions.

Создание веб-адреса в виде: example.com/Название_страницы:

Адреса вида - wiki.example.com/Название_страницы

Some people do not recommend this configuration. See Manual:Wiki in site root directory for potential problems and solutions.

Создание веб-адреса в виде: wiki.example.com/Page_title.

Разрешение проблем

Проблемы с амперсандом (&)

Объяснение: Эта проблема проявляется, когда у вас есть названия страниц с символами (например, &,?, #, + и /), которые, несмотря на правильное кодирование ссылки не правильно передается от mod_rewrite к скрипту. Это проявляется ошибкой 404 «Страница не найдена», потому что из заголовка вырезает особый символ, т.е. щелчок по ссылки "Джон & Мария" даст 404, потому MediaWiki ищет страницу с именем "Джон ".

Причиной проблемы является то, что амперсанд в названии статьи будет рассматриваться как разделитель строки запроса и никогда не попадет в окружающую среду выполнения PHP. Это вызвано старой и проблематичной ошибкой mod_rewrite.[1]

Решения:

This issue is caused by the ?title=$1 portion of rewrite rules like /index.php?title=$1 which is completely unnecessary and harmful. MediaWiki parses paths directly from the REQUEST_URI, so rewrite everything to /index.php.

Purging cache

If you notice that your changes to $wgArticlePath in LocalSettings.php are not being reflected in mysite.com/wiki/Main_Page, it may be due to MediaWiki's caching of the links according to previous settings.

Go to mysite.com/wiki/Main_Page?action=purge to force MediaWiki to regenerate the cached links.

Также вы можете:

  1. execute the MySQL query "TRUNCATE objectcache;", or
  1. Ensure $wgCacheEpoch is updated (if $wgInvalidateCacheOnLocalSettingsChange is enabled, all you have to do is edit LocalSettings.php to purge it)

Redirect visitor of your domain to your wiki

Our official guides for short url configuration include recommendations on how to point the root of your site to your wiki using your short url config.

For example our Apache guide recommends using this to point your site root to your wiki:

RewriteRule ^/*$ %{DOCUMENT_ROOT}/w/index.php [L]

Note that we do not recommend doing a HTTP redirect to your wiki path or main page directly. As redirecting to the main page directly will hard-code variable parts of your wiki's page setup into your server config. And redirecting to the wiki path will result in two redirects. Simply rewrite the root path to MediaWiki and it will take care of the 301 redirect to the main page itself.

If using VirtualHosts, place the rewrite rules into the virtual host declaration!

Moving a wiki from /wiki to /w

A common beginner's mistake is to install MediaWiki itself (the source code, not the short URL) in /wiki instead of /w. Once installed they would realize the mistake when trying to configure Short URLs (which would become difficult as the virtual path then conflicts with the real path).

There is a manual for moving a wiki in general, however that is too complicated if all you need is to change the installation directory (and stay on the same server, same database and same hostname).

Here is what you have to do:

  • Backup LocalSettings.php and any other config files you may have created (such as your .htaccess).
  • Rename the installation directory of MediaWiki on your server from /wiki to /w.
  • Set $wgScriptPath in LocalSettings.php to "/w" and remove (or comment out) any definition of $wgArticlePath (this variable will be changed again when setting up Short URLs, further on)
  • At this point your wiki should be working normally at example.org/w
  • Perform a few tests on your wiki to make sure nothing is broken.

Edit a page, visit a few different pages, etc. If anything seems abnormal, revert the changes by restoring your backup of LocalSettings.php and other relevant files you might have changed during configuration of short URLs and rename your folder back to /wiki.

Note for shared hosting users: Many shared hosting plans offer an application manager to automatically Install, Update and Backup applications such as MediaWiki. If your plan has this and if you want to keep using these features, you should contact their tech support and let them know you just manually changed your MediaWiki installation directory.

Полезные советы

См. также

  • $wgActionPaths - configuration setting that you can use to define 'pretty' URLs for other actions, like edit or history

Внешние ссылки

  • MediaWiki Short URL Builder Tool - A tool that can automatically generate a short url configuration more reliably than the configurations in these manual pages.

Технические примечания

  1. Bugzilla mod_rewrite для ошибки амперсанда, частично исправленной для некоторых пользователей, но только после 13 лет