Руководство:Короткие URL/Apache

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page Manual:Short URL/Apache and the translation is 22% complete.

Outdated translations are marked like this.
Other languages:
Deutsch • ‎English • ‎français • ‎polski • ‎русский • ‎中文 • ‎日本語 • ‎한국어
Wikipedia's short URLs.

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

The LiteSpeed webserver is Apache compatible and can be configured in relatively the same way. For information on what Short URLs are or to get instructions on configuration for other servers see Руководство:Удобные URL-адреса . If you don't know what webserver you're using since you're using some sort of web hosting service, it's very likely that your host is using Apache.

План

Перед началом работы необходимо определиться с именем виртуального пути "короткий url".

В этом руководстве мы рекомендуем/предполагаем следующее. Не забудьте использовать свои собственные пути, если они отличаются.

  • Каталог MediaWiki находится по адресу: /w
  • Требуемый формат короткого URL: /wiki/Page_title

Следующие инструкции были включены в автоматизированный мастер (требуется MediaWiki 1.17 или новее):

Если вы просто хотите, чтобы ваша вики была настроена быстро или вы обнаружили, что руководство запуталось, вы можете сначала попробовать этот инструмент. Обратите внимание, однако, что он не будет работать на брандмауэрах или в частных вики. В последнем случае вы все еще можете попробовать, сделав свою вики временно открытой, установив $code в значение $true. Не забудьте изменить его обратно на $false, как только вы закончите.

Please note, however, that it will not work on firewalled or private wikis. In the latter case, you can still try it out by making your wiki temporarily public by setting $wgGroupPermissions['*']['read'] to true. Remember to change it back to false once you are done.

В противном случае следуйте дальше.

Настройка сервера

Найдите нужный файл

Рекомендуется настроить короткие URL-адреса в Apache путем редактирования конфигурационных файлов Apache. Для этого требуется доступ к конфигурации сервера. Если вы находитесь на общем хосте, вы, скорее всего, не и нужно будет использовать файл $hta1 вместо этого. Использование файлов $hta2 менее эффективно и не дает вам столько контроля, когда дело доходит до причудливых настроек с несколькими доменами, но они достаточно мощны, чтобы настроить большинство коротких конфигураций url. Пользователи LiteSpeed должны использовать метод $hta3.

This requires that you have access to the server configuration. If you are on a shared host, you most likely don't and will need to use a .htaccess file instead. Using .htaccess files is less efficient and doesn't give you as much control when it comes to fancy setups with multiple domains but they are powerful enough to set up most short url configurations. LiteSpeed users should use the .htaccess method.

Используйте инструкции в одном из следующих двух разделов, в зависимости от того, есть ли у вас root-доступ или нужно использовать .htaccess вместо этого.

Найдите файл конфигурации Apache (root-доступ)

Корректный файл конфигурации для редактирования для корневых конфигураций может находиться в одном из нескольких мест.

Большинство дистрибутивов linux настраивают Apache с набором папок sites-available/ и sites-enabled/. Правильный конфигурационный файл для редактирования находится в $code3, где была настроена конфигурация для вашей Вики. Если Вы не настроили его и используете $code4 по умолчанию для настройки Вики, то вы можете отредактировать $code5.

The correct config file to edit is the one in /etc/apache2/sites-available/ where the configuration for your wiki has been setup. If you haven't set one up and are using the default /var/www for your wiki setup then you can edit /etc/apache2/sites-available/default.

Не забудьте включить переопределения с помощью AllowOverride All.

It is disabled by default in Ubuntu 12.04 and Ubuntu 12.10.

Если в вашем дистрибутиве нет этих каталогов, вы должны отредактировать файл конфигурации Apache напрямую. Этот файл должен быть в $code1. Обратите внимание, что это используется, чтобы быть названным $httpd1, если у вас есть $httpd2 и не $apache в $httpd3 является тот, который вы хотите редактировать.

This file should be at /etc/apache2/apache2.conf. Note that it used to be named httpd.conf, if you have a httpd.conf and no apache2.conf then httpd.conf is the one you want to edit.

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

Если вы находитесь на виртуальном хостинге без доступа к файлам конфигурации Apache вы должны использовать файл .htaccess вместо этого.

In an Apache config file you will likely have a VirtualHost block containing your wiki. If you do have one then that is the location where your rewrite rules will go. RewriteRule config does not inherit so don't put these config options in the global config if you are using a VirtualHost.

After you've setup the config as above inside Apache you're going to need to restart Apache to make it apply the new config.

  • If you are using Plesk or cPanel it should have a method of restarting the server.
  • From the command line the command is usually something like apache2ctl graceful, apachectl graceful, /etc/init.d/apache2 restart or as on the latest Fedora releases systemctl reload httpd.service. These commands need to be run as root, usually by prefixing them with sudo ....

Куда девать .htaccess

On Apache the AllowOverride controls whether .htaccess files are allowed to control server configuration. If these rewrite rules do nothing at all you may have to modify the AllowOverride setting in the Apache config to include FileInfo. It also requires Options FollowSymLinks for the directory.

If you're using a .htaccess file you'll need to edit or create the file. Find the path that contains both your script path and your virtual path. Usually this means the top directory of your site, but let's look at a few examples:

wgScript Example wgArticlePath Example .htaccess location
/w/index.php http://www.mediawiki.org/w/index.php?... /wiki/Page_title http://www.mediawiki.org/wiki/Manual:Short_URL /.htaccess
/w/index.php http://www.mediawiki.org/w/index.php?... /Page_title http://www.mediawiki.org/Manual:Short_URL /.htaccess
/mediawiki/index.php http://www.mediawiki.org/mediawiki/index.php?... /view/Article http://www.mediawiki.org/view/Manual:Short_URL /.htaccess
/mysite/mw/index.php http://www.mediawiki.org/mysite/mw/index.php?... /mysite/view/Page_title http://www.mediawiki.org/mysite/view/Manual:Short_URL /mysite/.htaccess

Note that if you want to make a redirect from the main domain to your wiki's Main Page (e.g. http://example.org/ → http://example.org/wiki/Main_Page). Then you always have to set up the .htaccess file in the top level, even if the other directories are nested deeper.

Setting up the rewrite rules

It's easier to understand the rest of this section after a glimpse at the Apache syntax, but this synopsis is not a substitute for the full Apache documentation:

RewriteCond TestString CondPattern
RewriteRule Pattern Substitution [flags]

The RewriteCond directive defines a condition that must be true before a RewriteRule that follows it may be applied. One or more RewriteCond directives may precede a RewriteRule directive, and all the RewriteCond directives that precede a RewriteRule must be true before that rule may be applied to a URI. In the examples that follow, TestString takes the form of a reference to server variables, e.g. %{ NAME_OF_VARIABLE }. Although many CondPatterns exist, the examples that follow use -f (true when TestString is a regular file) and -d (true when TestString is a directory), and they are preceded by a negation symbol, !.

The RewriteRule directive may be invoked in both the httpd.conf file and in any .htaccess file, but when the rewrite rule appears in .htaccess files, the implicit per-directory context affects the rule's Pattern because rules are relative to the current directory. In .htaccess files, Patterns are not relative to the complete, original URI. For .htaccess files, Patterns should never start with a forward slash, /, because the URI sub-string will never begin with a /. The examples that follow use the L flag whose meaning is Stop the rewriting process immediately, and don't apply any more rules.


The mod_rewrite module must be enabled in Apache or LiteSpeed servers for the examples that follow.
If you are using VirtualHosts, be sure that settings are placed inside the VirtualHost declaration

The first rule you'll need inside of your config is one to enable the rewrite engine:

RewriteEngine On

Now we need a rule to make your article path a virtual path pointing to index.php. Be sure to replace /wiki and /w/index.php with the paths you choose in the beginning (if different).

RewriteRule ^/?wiki(/.*)?$ %{DOCUMENT_ROOT}/w/index.php [L]
If you decide to customize this, be sure to never include ?title=$1 or something like it in the rewrite. Including a query will cause MediaWiki's built in handling to be overridden and will create bugs on your wiki due to the fact that Apache's query rewrites are broken.[1] The goal here is to alias paths to /index.php and then let MediaWiki itself take care of parsing and routing the url, based on the configuration in LocalSettings.php.

If you are using a root url instead of a normal short url you will need to use the following instead (to ensure that existing files and directories are not seen as article, e.g. "/index.php" "/images" etc.):

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule ^(.*)$ %{DOCUMENT_ROOT}/w/index.php [L]
If you are using a script path and article path that match such as /mywiki/index.php and /mywiki/Article you will also need to use the same two RewriteCond lines on your RewriteRule. However please note that there is no real valid reason to configure your wiki this way. If your article path is already a subdirectory you should just move your wiki's script path to another directory. Such as /w/index.php and /mywiki/Article or /my/index.php and /mywiki/Article.

Sometimes, the above example doesn't work. The following (you can't set this in a .htaccess, you need root access for this!) might work instead:

Alias /wiki /path/to/your/webroot/w/index.php

Optionally, you can include a rule to show the Main Page on the path itself, to simplify navigation when people visit urls without a page title specified:

# Redirect / to Main Page
RewriteRule ^/*$ %{DOCUMENT_ROOT}/w/index.php [L]

The end result should look something like this:

## https://www.mediawiki.org/wiki/Manual:Short_URL/Apache

# Enable the rewrite engine
RewriteEngine On

# Short URL for wiki pages
RewriteRule ^/?wiki(/.*)?$ %{DOCUMENT_ROOT}/w/index.php [L]

# Redirect / to Main Page
RewriteRule ^/*$ %{DOCUMENT_ROOT}/w/index.php [L]

or, if you used the way with the "Alias" statement:

## https://www.mediawiki.org/wiki/Manual:Short_URL/Apache

Alias /wiki /path/to/your/webroot/w/index.php
# Enable the rewrite engine
RewriteEngine On

# Redirect / to Main Page
RewriteRule ^/*$ %{DOCUMENT_ROOT}/w/index.php [L]
Make sure that the order of rules as given in the example is being preserved, i.e. "Short url for wiki pages" must be checked prior to "Redirect / to Main Page".
The ^/? in the config is important because different Apache setups use different regexps. Some want you to use ^wiki/ and some want you to use ^/wiki/. The ? in /? allows this rule to work in both contexts.
The %{DOCUMENT_ROOT} in the config ensures that Apache has the correct non-ambiguous path. However it does not work on some badly configured free hosts. If you have 404 or 403 issues with your RewriteRules, remove the %{DOCUMENT_ROOT} parts and try again.
If your SCRIPT_PATH leads to some other physical location (known as "symlink" in Unix, "shortcut" on Windows, "alias" in Mac OS X), you may need to allow Apache to follow those. You can do so by adding this line above the RewriteEngine:
Options +FollowSymLinks
If the path to your script directory is aliased by the webserver via an Alias directive, as it is in Debian among others, the RewriteRule will work as long as you add the PT flag (ie: change [L] to [PT,L]) to Pass Through the request to the next handler - mod_alias, which will correctly redirect the request, as per Stack Overflow

LocalSettings.php

We need to make the following configurations in LocalSettings.php:

## https://www.mediawiki.org/wiki/Manual:Short_URL
$wgScriptPath = "/w";        // this should already have been configured this way
$wgArticlePath = "/wiki/$1";

If you get an "Internal error" page saying "Redirect loop detected!" after you finish configuration you may be using something other than mod_php. If so you need to explicitly turn on short urls using the following line in your LocalSettings.php:

$wgUsePathInfo = true;

If there is still an "internal error" check the log files of your server. Maybe you have to turn on mod_rewrite module.

См. также

Примечания