Manual:Short URL

From mediawiki.org
This page is a translated version of the page Manual:Short URL and the translation is 42% complete.
Outdated translations are marked like this.
Este artigo é sobre a estrutura de URL. Para criar URLs curtos para artigos, consulte Extensão:ShortUrl . Para criar um serviço de redução de URL, consulte Extension:UrlShortener .

Short URLs ou URL Rewrites escondem a extensão php dos arquivos no endereço da página. Por favor, dedique alguns minutos criando uma estrutura estável de URL para seu site antes de começar, para evitar problemas futuros.

Introdução

Objetivo

O caminho de instalação padrão do MediaWiki geralmente parece com isso:

/var/www/html/mediawiki (instalado como usuário root)
/home/johndoe/public_html/mediawiki (instalado em um provedor de hospedagem compartilhada)

Os endereços da página padrão do MediaWiki parecem com estes exemplos:

https://example.org/w/index.php/Page_title (versões mais recentes do MediaWiki, sem suporte CGI)
https://example.org/w/index.php?title=Page_title (versões mais recentes do MediaWiki, com suporte CGI)

Usando os métodos abordados nesta página, podemos configurar para algo assim:

https://example.org/wiki/Page_title Esta é a configuração mais comum, o mesmo que a Wikipédia, embora não seja a padrão porque requer algumas modificações no lado servidor.
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.

Vantagens e desvantagens

  • Vantagem: Short URLs escondem alguns detalhes técnicos dos usuários finais, o que pode ser desejável para os donos do site. Entre outras coisas, isto significa que eles podem manter-se estáveis quando o software por baixo deles mudar. (Veja acima a diferença entre a estrutura de URL padrão do MediaWiki com CGI habilitado vc não-habiltado) Também são mais fáceis de ler, lembrar e manipular pelos visitantes. Além disso, short URLs tem a vantagem sobre as URLs padrão de pt:Otimização para motores de busca, já que URLs contendo ? podem ser tratadas de modo menos favoráveis por engines de busca ao calcular a colocação da página.
  • Desvantagem: Precisa ser configurado, então, dependendo do ambiente de servidor que você está usando, pode ser difícil de recriar. Entretanto, como todo servidor web amplamente usado é capaz de ser configurado para short URLs, a maioria dos serviços de hospedagem pagos devem suportar este recurso. Qualquer hospedagem que não ofereça este recurso não vale seu dinheiro.

Guias

Nossos guias oficiais para configuração de short URL para diferentes servidores web. Escolha a configuração do seu servidor web na lista. Se voê não sabe que software servidor está usando, então provavelmente é o Apache.

Outros mini-guias de como-fazer

These guides are old and are almost entirely bad advice. These will eventually be deleted one by one as our official guides above are created for different webservers.

Anyone is welcome to create a how-to solution page and list it below. Please use a sensible name for the page, one that fits in with the below names. 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.

URL like - example.com/wiki/Page_title

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

Root access

These methods require that you have access to the server configuration. If you are on a shared host, you most likely don't. In this case you will be required to use a method that requires "no root access". 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).

URL like - example.com/Page_title

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

How to create example.com/Page_title URLs:

URL like - wiki.example.com/Page_title

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

How to create wiki.example.com/Page_title URLs:

Troubleshooting

Ampersand (&) problem

The ampersand problem shows up when you have page titles with symbols in them (such as &, ?, #, + and /) which, despite being correctly encoded in the link, are not being passed correctly from mod_rewrite to the script. This manifests in 404 page-not-found errors, because the title gets cut off at the special character. For example, clicking on a link to "John & Maria's page" gets a 404, because MediaWiki is looking for a page named "John ".

This is because ampersands in long-form names are treated as query string separators, and would never reach the PHP runtime environment. This is caused by an old and problematic mod_rewrite bug.[1]

Solution:

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.

Also you can:

  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!

Movendo um wiki de /wiki para /w

Um erro comum do iniciante é instalar o próprio MediaWiki (o código-fonte, não o URL curto) em /wiki em vez de /w. Uma vez instalados, eles perceberiam o erro ao tentar configurar URLs curtos (o que se tornaria difícil, pois o caminho virtual entra em conflito com o caminho real).

Existe um manual para movendo um wiki em geral, porém isso é muito complicado se tudo o que você precisa é mudar o diretório de instalação (e permanecer no mesmo servidor, mesmo banco de dados e mesmo nome de host).

Aqui está o que você deve fazer:

  • Faça backup de LocalSettings.php e quaisquer outros arquivos de configuração que você possa ter criado (como seu .htaccess).
  • Renomeie o diretório de instalação do MediaWiki em seu servidor de /wiki para /w.
  • Defina $wgScriptPath em LocalSettings.php como "/w" e remova (ou comente) qualquer definição de $wgArticlePath (esta variável será alterada novamente ao configurar URLs curtos, mais adiante)
  • Neste ponto, seu wiki deve estar funcionando normalmente em example.org/w
  • Agora vá até o guia regular para configurar URLs curtos
  • Execute alguns testes em seu wiki para ter certeza de que nada está quebrado. Edite uma página, visite algumas páginas diferentes, etc. Se algo parecer anormal, reverta as alterações restaurando seu backup de LocalSettings.php e outros arquivos relevantes que você possa ter alterado durante a configuração de URLs curtos e renomeie sua pasta de volta para /wiki.

Nota para usuários de hospedagem compartilhada: Muitos planos de hospedagem compartilhada oferecem um gerenciador de aplicativos para automaticamente instalar, atualizar e fazer backup de aplicativos como o MediaWiki. Se o seu plano tem isso e se você deseja continuar usando esses recursos, você deve entrar em contato com o suporte técnico e informá-los que você acabou de alterar manualmente o diretório de instalação do MediaWiki.

Tricks

See also

  • $wgUsePathInfo - configuration setting that defines whether to use 'pretty' URLs or not
  • $wgActionPaths - definição de configuração que você pode usar para definir URLs 'bonitas' para outras ações, como editar ou histórico.

External links

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

References

  1. Bugzilla mod_rewrite for ampersand bug, partially resolved for some users, but only after 13 years