{"id":15483,"date":"2019-04-17T10:30:52","date_gmt":"2019-04-17T13:30:52","guid":{"rendered":"https:\/\/blog.hostinger.io\/br-tutoriais\/?p=15483"},"modified":"2024-05-16T17:05:10","modified_gmt":"2024-05-16T20:05:10","slug":"configurar-mod-rewrite","status":"publish","type":"post","link":"\/br\/tutoriais\/configurar-mod-rewrite","title":{"rendered":"Como configurar o mod_rewrite do Apache e ter URLs amig\u00e1veis"},"content":{"rendered":"<p><span style=\"font-weight: 400\">O<\/span><b> mod_rewrite<\/b><span style=\"font-weight: 400\"> do <a href=\"https:\/\/www.hostinger.com\/br\/tutoriais\/o-que-e-apache\" target=\"_blank\" rel=\"noopener noreferrer\">Apache<\/a> &eacute; uma maneira f&aacute;cil e eficiente de manipular URLs. A manipula&ccedil;&atilde;o de URLs &eacute; feita pelo lado do servidor.<\/span><\/p><p><span style=\"font-weight: 400\">Numa explica&ccedil;&atilde;o simples, com o mod_rewrite, URLs amig&aacute;veis, simples e sem caracteres especiais s&atilde;o convertidas em sites.<\/span><\/p><p><span style=\"font-weight: 400\">Como o pr&oacute;prio nome sugere, o que ele faz &eacute; reescrever a URL. E isso pode ser uma &oacute;tima maneira de limpar e organizar as URLs do seu site.<\/span><\/p><p><span style=\"font-weight: 400\">Neste tutorial, vamos explicar o que &eacute; mod_rewrite, por que ele &eacute; &uacute;til e como configurar a ferramenta numa VPS rodando no Apache.<\/span><\/p><h2 id=\"h-como-o-mod_rewrite-apache-funciona\"><b>Como o Mod_Rewrite Apache funciona?<\/b><\/h2><p><span style=\"font-weight: 400\">Todas as vezes que o usu&aacute;rio insere uma URL no navegador, ela &eacute; verificada dentro uma lista de regras pr&eacute;-definidas. <\/span><\/p><p><span style=\"font-weight: 400\">As regras est&atilde;o presentes para procurar por algum padr&atilde;o espec&iacute;fico ou at&eacute; mesmo palavras-chaves. <\/span><\/p><p><span style=\"font-weight: 400\">Se uma palavra-chave est&aacute; presente em uma URL e a regra corresponder, ela &eacute; substitu&iacute;da com uma sequ&ecirc;ncia pr&eacute;-definida &ndash; uma nova URL.<\/span><\/p><h2 id=\"h-o-que-torna-o-mod_rewrite-util\"><b>O Que Torna o Mod_Rewrite &Uacute;til?<\/b><\/h2><p><span style=\"font-weight: 400\">A maior vantagem do mod-rewrite &eacute; que ele oferece a habilidade de manipular URLs. Principalmente se voc&ecirc; tem uma URL complicada e deseja deix&aacute;-la limpa em uma nova URL. <\/span><\/p><p><span style=\"font-weight: 400\">Essas novas URLs tamb&eacute;m s&atilde;o amig&aacute;veis ao usu&aacute;rio final e aos motores de busca. Isso significa que eles v&atilde;o reconhecer essas nova URLs muito mais rapidamente. <\/span><\/p><p><span style=\"font-weight: 400\">Mas o que &eacute; uma URL limpa? Vamos dar uma olhada nos exemplos abaixo.<\/span><\/p><ol>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\"><strong>URL1<\/strong>: <\/span><span style=\"font-weight: 400\">http:\/\/modrewriteexample.com\/client.php?id=A786#234QA<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\"><strong>URL2<\/strong>: <\/span><span style=\"font-weight: 400\">http:\/\/modrewriteexample.com\/client\/=A786#234QA\/<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\"><strong>URL3<\/strong>: <\/span><span style=\"font-weight: 400\">http:\/\/modrewriteexample.com\/client\/Martha\/<\/span><\/li>\n<\/ol><p><span style=\"font-weight: 400\">De todas as tr&ecirc;s URLS listadas acima, est&aacute; claro que a terceira &eacute; uma URL muito mais f&aacute;cil de ler e ser melhor entendida pelo usu&aacute;rio do que as outras duas. Neste caso, a URL 3 &eacute; uma URL limpa.<\/span><\/p><h2 id=\"h-como-configurar-mod_rewrite-numa-vps-linux\"><b>Como Configurar Mod_Rewrite numa VPS Linux?<\/b><\/h2><p><span style=\"font-weight: 400\">Antes de come&ccedil;armos, voc&ecirc; vai precisar de acesso a sua VPS usando SSH. Se precisar de ajuda nesse processo, use nosso <\/span><a href=\"https:\/\/www.hostinger.com\/br\/tutoriais\/como-se-conectar-servidor-vps-usando-terminal-ssh\/\"><span style=\"font-weight: 400\">tutorial PuTTy<\/span><\/a><span style=\"font-weight: 400\">. Agora, vamos partir para a configura&ccedil;&atilde;o.<\/span><\/p><h3><b>1. Instalar o Apache<\/b><\/h3><p><span style=\"font-weight: 400\">Vamos usar o Ubuntu para este exemplo. Ele tem um pacote de instalador nativo, que se chama <\/span><b>apt-get<\/b><span style=\"font-weight: 400\">. Primeirol, vamos atualiz&aacute;-lo executando o comando:<\/span><\/p><pre><span style=\"font-weight: 400\">sudo apt-get update<\/span><\/pre><p><span style=\"font-weight: 400\">Agora, podemos proceder com a instala&ccedil;&atilde;o do Apache. O comando para isso &eacute;:<\/span><\/p><pre><span style=\"font-weight: 400\">sudo apt-get install apache2<\/span><\/pre><h3><b>2. Habilitar o Mod_Rewrite<\/b><\/h3><p><span style=\"font-weight: 400\">Agora, precisamos habilitar o mod_rewrite. O comando para isso &eacute;:<\/span><\/p><pre><span style=\"font-weight: 400\">sudo a2enmod rewrite<\/span><\/pre><p><span style=\"font-weight: 400\">O comando acima vai habilitar o modo de reescrever ou informar que ele j&aacute; est&aacute; em uso. Depois disso, reinicie o Apache. <\/span><\/p><pre><span style=\"font-weight: 400\">sudo service apache2 restart<\/span><\/pre><h3><b>3. Criar o Arquivo .htaccess<\/b><\/h3><p><span style=\"font-weight: 400\">As regras para reescrever URLs devem ser pr&eacute;-definidas. Aqui, o <\/span><b>.htaccess <\/b><span style=\"font-weight: 400\">aparece. Um usu&aacute;rio pode escrever todas as regras em um arquivo <\/span><b>.htaccess<\/b><span style=\"font-weight: 400\">. <\/span><\/p><p><span style=\"font-weight: 400\">Ele &eacute; usado pelo servidor. N&atilde;o deve haver erros nesse arquivos, se n&atilde;o o servidor vai apontar o erro. Podemos modificar nossas regras reescritas a qualquer momento. <\/span><\/p><p><span style=\"font-weight: 400\">O arquivo<\/span><b> .htaccess<\/b><span style=\"font-weight: 400\"> deve ser criado na raiz para testar a funcionalidade de reescrever. Para isso, execute o comando:<\/span><\/p><pre><span style=\"font-weight: 400\">sudo nano \/var\/www\/html\/.htaccess<\/span><\/pre><p><span style=\"font-weight: 400\">Isso vai criar o arquivo <\/span><b>.htaccess<\/b><span style=\"font-weight: 400\">, se ele ainda n&atilde;o tiver sido criado, ou abri-lo, se ele j&aacute; existir. Agora, podemos salvar e sair. No nano, voc&ecirc; pode fazer essa mesma opera&ccedil;&atilde;o apertando <\/span><b>CTRL+O<\/b><span style=\"font-weight: 400\"> para salvar e <\/span><b>CTRL+X<\/b><span style=\"font-weight: 400\"> para sair. <\/span><\/p><p><span style=\"font-weight: 400\">Agora, precisamos abrir o arquivo 000-default.conf localizado no diret&oacute;rio <\/span><b>\/etc\/apache2\/sites-enabled\/<\/b><span style=\"font-weight: 400\">. O comando para fazer isso &eacute;:<\/span><\/p><pre><span style=\"font-weight: 400\">sudo nano \/etc\/apache2\/sites-enabled\/000-default.conf<\/span><\/pre><p><span style=\"font-weight: 400\">Dentro deste arquivo, coloque o bloco de texto abaixo usando a linha <\/span><b>&lt;VirtualHost *:80&gt;<\/b><span style=\"font-weight: 400\">:<\/span><\/p><pre><span style=\"font-weight: 400\">&lt;Directory \/var\/www\/html&gt;<\/span>\r\n<span style=\"font-weight: 400\">Options Indexes FollowSymLinks MultiViews<\/span>\r\n<span style=\"font-weight: 400\">AllowOverride All<\/span>\r\n<span style=\"font-weight: 400\">Order allow, deny<\/span>\r\n<span style=\"font-weight: 400\">allow from all<\/span>\r\n<span style=\"font-weight: 400\">&lt;\/Directory&gt;<\/span><\/pre><p><span style=\"font-weight: 400\">Salve o arquivo como voc&ecirc; fez com o <strong>.htaccess<\/strong>. Para as mudan&ccedil;as acima surtirem efeito, reinicie o Apache como mostrado no final do passo 2.<\/span><\/p><h2 id=\"h-4-reescrever-a-url\"><b>4. Reescrever a URL<\/b><\/h2><p><span style=\"font-weight: 400\">Reescrever a URL &eacute; basicamente escolher a URL limpa e convert&ecirc;-la em caminhos reais que levam ao c&oacute;digo ou site esperado. Ela deve ter:<\/span><\/p><ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Uma regra de reescrita pr&eacute;-definida;<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Um padr&atilde;o &ndash; o padr&atilde;o fornecido vai agir como uma refer&ecirc;ncia combinada com a URL inserida pelo usu&aacute;rio;<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Linhas de reescrita &ndash; ela vai solicitar o caminho que deve ser chamado no momento pedido pelo servidor.<\/span><\/li>\n<\/ul><p><span style=\"font-weight: 400\">Agora, vamos escrever uma regra de reescrita que vai direcionar o usu&aacute;rio para a p&aacute;gina About_us.html, se a URL requisitada for <\/span><a href=\"http:\/\/ip\/Aboutus\"><span style=\"font-weight: 400\">http:\/\/ip\/Aboutus<\/span><\/a><span style=\"font-weight: 400\">.<\/span><\/p><p><span style=\"font-weight: 400\">Para escrever a regra de reescrita com sucesso, o motor de reescrita deve estar ligado. Insira o comando abaixo no come&ccedil;o do arquivo <\/span><b>.htaccess<\/b><span style=\"font-weight: 400\">. <\/span><\/p><pre><span style=\"font-weight: 400\">RewriteEngine on<\/span><\/pre><p><span style=\"font-weight: 400\">O pr&oacute;ximo comando pode ser a nossa regra:<\/span><\/p><pre><span style=\"font-weight: 400\">ReWriteRule ^About_us$ Aboutus.html [NC]<\/span><\/pre><p><span style=\"font-weight: 400\">A sintaxe pode ser um pouco confusa, ent&atilde;o vamos separ&aacute;-la por partes.<\/span><\/p><ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Na regra acima, &ldquo;About_us&rdquo; &eacute; o padr&atilde;o que, quando encontrado e correspondido, ser&aacute; redirecionado para <\/span><b>About_us.html<\/b><span style=\"font-weight: 400\">. &nbsp;<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">&ldquo;NC&rdquo; &eacute; um sinalizador que faz com que a regra seja insens&iacute;vel a letras mai&uacute;sculas ou min&uacute;sculas.<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">&ldquo;^&rdquo; retrata que o texto imediatamente ap&oacute;s o endere&ccedil;o de IP &eacute; correspondido.<\/span><\/li>\n<\/ul><p><span style=\"font-weight: 400\">As duas linhas combinadas se pareceriam com isso no arquivo <\/span><b>.htaccess<\/b><span style=\"font-weight: 400\">: <\/span><\/p><pre><span style=\"font-weight: 400\">ReWriteEngine on<\/span><\/pre><pre><span style=\"font-weight: 400\">ReWriteRule ^About_us$ Abouts_us.html [NC]<\/span><\/pre><p><span style=\"font-weight: 400\">E isso &eacute; tudo! Criamos com sucesso uma regra mod_rewrite!<\/span><\/p><h2 id=\"h-conclusao\"><b>Conclus&atilde;o<\/b><\/h2><p><span style=\"font-weight: 400\">URLs f&aacute;ceis e amig&aacute;veis ao usu&aacute;rio tem um papel vital no sucesso de um site. Ter as palavras-chaves &eacute; muito importante, n&atilde;o apenas URLs memor&aacute;veis, mas voc&ecirc; precisa pensar no SEO tamb&eacute;m. <\/span><\/p><p><span style=\"font-weight: 400\">Existem centenas de regras que voc&ecirc; pode criar e escrever. E agora voc&ecirc; sabe como fazer isso! Esperamos que voc&ecirc; fa&ccedil;a bom uso do mod_rewrite. At&eacute; o pr&oacute;ximo tutorial. \ud83d\ude09<\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>O mod_rewrite do Apache &eacute; uma maneira f&aacute;cil e eficiente de manipular URLs. A manipula&ccedil;&atilde;o de URLs &eacute; feita pelo lado do servidor.Numa explica&ccedil;&atilde;o simples, com o mod_rewrite, URLs amig&aacute;veis, simples e sem caracteres especiais s&atilde;o convertidas em sites.Como o pr&oacute;prio nome sugere, o que ele faz &eacute; reescrever a URL. E isso pode ser [&#8230;]<\/p>\n<p><a class=\"btn btn-secondary understrap-read-more-link\" href=\"\/br\/tutoriais\/configurar-mod-rewrite\">Read More&#8230;<\/a><\/p>\n","protected":false},"author":92,"featured_media":15488,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"rank_math_title":"","rank_math_description":"Saber usar o mod_rewrite do Apache permite que voc\u00ea crie URLs bem mais amig\u00e1veis na sua VPS. Aprenda agora como fazer!","rank_math_focus_keyword":"mod_rewrite","footnotes":""},"categories":[4915],"tags":[4864,6483,6484,6485],"class_list":["post-15483","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-vps","tag-apache","tag-mod_rewrite","tag-reescrever-url","tag-url-amigavel"],"hreflangs":[{"locale":"pt-BR","link":"https:\/\/www.hostinger.com\/br\/tutoriais\/configurar-mod-rewrite","default":1},{"locale":"pt-PT","link":"https:\/\/www.hostinger.com\/pt\/tutoriais\/configurar-mod-rewrite","default":0}],"acf":[],"_links":{"self":[{"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/posts\/15483","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/users\/92"}],"replies":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/comments?post=15483"}],"version-history":[{"count":10,"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/posts\/15483\/revisions"}],"predecessor-version":[{"id":49555,"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/posts\/15483\/revisions\/49555"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/media\/15488"}],"wp:attachment":[{"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/media?parent=15483"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/categories?post=15483"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.hostinger.com\/br\/tutoriais\/wp-json\/wp\/v2\/tags?post=15483"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}