One place for hosting & domains

      modrewrite

      How to Rewrite URLs with mod_rewrite for Apache on Ubuntu 20.04


      Not using Ubuntu 20.04?


      Choose a different version or distribution.

      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Apache’s mod_rewrite module lets you rewrite URLs more cleanly, translating human-readable paths into code-friendly query strings. It also enables you to rewrite URLs based on conditions.

      An .htaccess file lets you create and apply rewrite rules without accessing server configuration files. By placing the .htaccess file in the root of your web site, you can manage rewrites on a per-site or per-directory basis.

      In this tutorial, you’ll enable mod_rewrite and use .htaccess files to create a basic URL redirection, and then explore a couple of advanced use cases.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Enabling mod_rewrite

      In order for Apache to understand rewrite rules, we first need to activate mod_rewrite. It’s already installed, but it’s disabled on a default Apache installation. Use the a2enmod command to enable the module:

      This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.

      • sudo systemctl restart apache2

      mod_rewrite is now fully enabled. In the next step, we will set up an .htaccess file that we’ll use to define rewrite rules for redirects.

      Step 2 — Setting Up .htaccess

      An .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web application’s security. The period that precedes the filename ensures that the file is hidden.

      Note: Any rules that you can put in an .htaccess file can be also put directly into server configuration files. In fact, the official Apache documentation recommends using server configuration files instead of .htaccess because Apache processes it faster that way.

      However, in this simple example, the performance increase will be negligible. Additionally, setting rules in .htaccess is convenient, especially with multiple websites on the same server. It does not require a server restart for changes to take effect and it does not require root privileges to edit those rules, simplifying maintenance and making changes possible with an unprivileged account. Some popular open-source software, like WordPress and Joomla, often relies on an .htaccess file for the software to modify and create additional rules on demand.

      Before you start using .htaccess files, you’ll need to set up and secure a few more settings.

      By default, Apache prohibits using an .htaccess file to apply rewrite rules, so first you need to allow changes to the file. Open the default Apache configuration file using nano or your favorite text editor.

      • sudo nano /etc/apache2/sites-available/000-default.conf

      Inside that file, you will find a <VirtualHost *:80> block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented.

      /etc/apache2/sites-available/000-default.conf

      <VirtualHost *:80>
          <Directory /var/www/html>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
          </Directory>
      
          . . .
      </VirtualHost>
      

      Save and close the file. To put these changes into effect, restart Apache.

      • sudo systemctl restart apache2

      Now, create an .htaccess file in the webroot.

      • sudo nano /var/www/html/.htaccess

      Add this line at the top of the new file to activate the rewrite engine.

      /var/www/html/.htaccess

      RewriteEngine on
      

      Save the file and exit.

      We now have an operational .htaccess file that we can use to govern our web application’s routing rules. In the next step, we will create sample website files that we’ll use to demonstrate rewrite rules.

      Step 3 — Configuring URL Rewrites

      Here, we will set up a basic URL rewrite that converts pretty URLs into actual paths to pages. Specifically, we will allow users to access http://your_server_ip/about, but display a page called about.html.

      Begin by creating a file named about.html in the webroot.

      • sudo nano /var/www/html/about.html

      Copy the following HTML code into the file, then save and close it.

      /var/www/html/about.html

      <html>
          <head>
              <title>About Us</title>
          </head>
          <body>
              <h1>About Us</h1>
          </body>
      </html>
      

      You can access this page at http://your_server_ip/about.html, but notice that if you try to access http://your_server_ip/about, you will see a 404 Not Found error. To access the page using /about instead, we’ll create a rewrite rule.

      All RewriteRules follow this format:

      General RewriteRule structure

      RewriteRule pattern substitution [flags]
      
      • RewriteRule specifies the directive.
      • pattern is a regular expression that matches the desired string from the URL, which is what the viewer types in the browser.
      • substitution is the path to the actual URL, i.e., the path of the file Apache servers.
      • flags are optional parameters that can modify how the rule works.

      Let’s create our URL rewrite rule. Open up the .htaccess file.

      • sudo nano /var/www/html/.htaccess

      After the first line, add the highlighted RewriteRule and save the file.

      /var/www/html/.htaccess

      RewriteEngine on
      RewriteRule ^about$ about.html [NC]
      

      In this case, ^about$ is the pattern, about.html is the substitution, and [NC] is a flag. Our example uses a few characters with special meaning:

      • ^ indicates the start of the URL after your_server_ip/.
      • $ indicates the end of the URL.
      • about matches the string “about”.
      • about.html is the actual file that the user accesses.
      • [NC] is a flag that makes the rule case insensitive.

      You can now access http://your_server_ip/about in your browser. In fact, with the rule shown above, the following URLs will point to about.html:

      • http://your_server_ip/about, because of the rule definition.
      • http://your_server_ip/About, because the rule is case insensitive.
      • http://your_server_ip/about.html, because the original proper filename will always work.

      However, the following will not work:

      • http://your_server_ip/about/, because the rule explicitly states that there may be nothing after about, since the $ character appears after about.
      • http://your_server_ip/contact, because it won’t match the about string in the rule.

      You now have an operational .htaccess file with a basic rule that you can modify and extend to your needs. In the following sections, we will show two additional examples of commonly used directives.

      Example 1 — Simplifying Query Strings with RewriteRule

      Web applications often make use of query strings, which are appended to a URL using a question mark (?) after the address. Separate parameters are delimited using an ampersand (&). Query strings may be used for passing additional data between individual application pages.

      For example, a search result page written in PHP may use a URL like http://example.com/results.php?item=shirt&season=summer. In this example, two additional parameters are passed to the imaginary result.php application script: item, with the value shirt, and season with the value summer. The application may use the query string information to build the right page for the visitor.

      Apache rewrite rules are often employed to simplify such long and unpleasant links as the above into friendly URLs that are easier to type and interpret visually. In this example, we would like to simplify the above link to become http://example.com/shirt/summer. The shirt and summer parameter values are still in the address but without the query string and script name.

      Here’s one rule to implement this:

      Simple substitution

      RewriteRule ^shirt/summer$ results.php?item=shirt&season=summer [QSA]
      

      The shirt/summer is explicitly matched in the requested address and Apache is told to serve results.php?item=shirt&season=summer instead.

      The [QSA] flags are commonly used in rewrite rules. They tell Apache to append any additional query string to the served URL, so if the visitor types http://example.com/shirt/summer?page=2 the server will respond with results.php?item=shirt&season=summer&page=2. Without it, the additional query string would get discarded.

      While this method achieves the desired effect, both the item name and season are hardcoded into the rule. This means the rule will not work for any other items, like pants, or seasons, like winter.

      To make the rule more generic, we can use regular expressions to match parts of the original address and use those parts in a substitution pattern. The modified rule will then look as follows:

      Simple substitution

      RewriteRule ^([A-Za-z0-9]+)/(summer|winter|fall|spring) results.php?item=$1&season=$2 [QSA]
      

      The first regular expression group in parenthesis matches a string containing alphanumeric characters and numbers like shirt or pants and saves the matched fragment as the $1 variable. The second regular expression group in parenthesis matches exactly summer, winter, fall, or spring, and similarly saves the matched fragment as $2.

      The matched fragments are then used in the resulting URL in item and season variables instead of hardcoded shirt and summer values we used before.

      The above will convert, for example, http://example.com/pants/summer into http://example.com/results.php?item=pants&season=summer. This example is also future proof, allowing multiple items and seasons to be rewritten correctly using a single rule.

      Example 2 — Adding Conditions with Logic Using RewriteConds

      Rewrite rules are not necessarily always evaluated one by one without any limitations. The RewriteCond directive lets us add conditions to our rewrite rules to control when the rules are processed. All RewriteConds abide by the following format:

      General RewriteCond structure

      RewriteCond TestString Condition [Flags]
      
      • RewriteCond specifies the RewriteCond directive.
      • TestString is the string to test against.
      • Condition is the pattern or condition to match.
      • Flags are optional parameters that may modify the condition and evaluation rules.

      If a RewriteCond evaluates to true, the RewriteRule immediately following will be considered. If it won’t, the rule will be discarded. Multiple RewriteCond may be used one after another and, with default behavior, all must evaluate to true for the following rule to be considered.

      As an example, let’s assume you would like to redirect all requests to non-existent files or directories on your site back to the home page instead of showing the standard 404 Not Found error page. This can be achieved with following conditions rules:

      Redirect all requests to non-existent files and directories to home page

      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . / [R=301]
      

      With the above:

      • %{REQUEST_FILENAME} is the string to check. In this case, it’s the requested filename, which is a system variable available for every request.
      • -f is a built-in condition that verifies if the requested name exists on disk and is a file. The ! is a negation operator. Combined, !-f evaluates to true only if a specified name does not exist or is not a file.
      • Similarly, !-d evaluates to true only if a specified name does not exist or is not a directory.

      The RewriteRule on the final line will come into effect only for requests to non-existent files or directories. The RewriteRule itself is very simple. The dot . in the pattern matches anything and the substitution directs every request to the / website root.

      Additionally, [R=301] flag tells Apache to return a 301 Moved Permanently redirect HTTP response code to the browser, resulting in a browser knowing the redirect happened and explicitly fetching the website root instead of the requested URL, with the change being reflected on the browser address bar.

      Without this flag, Apache would return the website root contents, but the browser would still think the requested page URL exists and would show the originally requested address on the address bar.

      mod_rewrite lets you create human-readable URLs. In this tutorial, you used the RewriteRule directive to redirect URLs, including ones with query strings. You also wrote conditionally redirecting URLs using the RewriteCond directive.

      If you’d like to learn more about mod_rewrite, take a look at Apache’s mod_rewrite Introduction and Apache’s official documentation for mod_rewrite.



      Source link

      Como Reescrever URLs com mod_rewrite para Apache no Debian 10


      Introdução

      O módulo mod_rewrite do Apache permite reescrever URLs de uma maneira mais limpa, traduzindo caminhos legíveis por humanos em strings de consulta ou query strings amigáveis ao código. Também permite reescrever URLs com base em condições.

      Um arquivo .htaccess lhe permite criar e aplicar regras de reescrita sem acessar os arquivos de configuração do servidor. Ao colocar o arquivo .htaccess na raiz do seu site, você pode gerenciar as reescritas por site ou por diretório.

      Neste tutorial, você habilitará o mod_rewrite e usará arquivos .htaccess para criar um redirecionamento básico de URL e depois explorar alguns casos de uso avançados.

      Pré-requisitos

      Para seguir este tutorial, você precisará de:

      Passo 1 — Ativando o mod_rewrite

      Para que o Apache entenda as regras de reescrita, primeiro precisamos ativar o mod_rewrite. Ele já está instalado, mas está desativado em uma instalação padrão do Apache. Use o comando a2enmod para ativar o módulo:

      Isso ativará o módulo ou o alertará que o módulo já está ativado. Para colocar essas alterações em vigor, reinicie o Apache:

      • sudo systemctl restart apache2

      O mod_rewrite está agora totalmente ativado. Na próxima etapa, configuraremos um arquivo .htaccess que usaremos para definir regras de reescrita para redirecionamentos.

      Passo 2 — Configurando o .htaccess

      Um arquivo .htaccess nos permite modificar nossas regras de reescrita sem acessar os arquivos de configuração do servidor. Por esse motivo, o .htaccess é fundamental para a segurança de sua aplicação web. O ponto que precede o nome do arquivo garante que o mesmo esteja oculto.

      Nota: Quaisquer regras que você possa colocar em um arquivo .htaccess também podem ser colocadas diretamente nos arquivos de configuração do servidor. De fato, a documentação oficial do Apache recomenda o uso de arquivos de configuração do servidor em vez do .htaccess, devido aos tempos de processamento mais rápidos.

      No entanto, neste exemplo simples, o aumento de desempenho será desprezível. Além disso, definir regras no .htaccess é conveniente, especialmente com vários sites no mesmo servidor. Não é necessário reiniciar o servidor para que as alterações tenham efeito ou privilégios de root para editar regras, simplificando a manutenção e o processo de fazer alterações com uma conta sem privilégios. Softwares open-source populares como WordPress e Joomla contam com arquivos .htaccess para fazer modificações e regras adicionais sob demanda.

      Antes de começar a usar arquivos .htaccess, você precisará configurar e proteger mais algumas configurações.

      Por padrão, o Apache proíbe o uso de um arquivo .htaccess para aplicar regras de reescrita, portanto, primeiro você precisa permitir alterações no arquivo. Abra o arquivo de configuração padrão do Apache usando nano ou seu editor de texto favorito:

      • sudo nano /etc/apache2/sites-available/000-default.conf

      Dentro desse arquivo, você encontrará um bloco <VirtualHost *:80> iniciando na primeira linha. Dentro desse bloco, adicione o novo bloco a seguir para que seu arquivo de configuração se pareça com o seguinte. Verifique se todos os blocos estão identados corretamente:

      /etc/apache2/sites-available/000-default.conf

      <VirtualHost *:80>
          <Directory /var/www/html>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
          </Directory>
      
          . . .
      </VirtualHost>
      

      Salve e feche o arquivo. Se você usou o nano, faça isso pressionando CTRL+X, Y e, em seguida, ENTER.

      Em seguida, verifique sua configuração:

      • sudo apache2ctl configtest

      Se não houver erros, reinicie o Apache para efetivar suas alterações:

      • sudo systemctl restart apache2

      Agora, crie um arquivo .htaccess na raiz dos arquivos web, também chamado de web root:

      • sudo nano /var/www/html/.htaccess

      Adicione esta linha na parte superior do novo arquivo para ativar o mecanismo de reescrita.

      /var/www/html/.htaccess

      RewriteEngine on
      

      Salve o arquivo e saia.

      Agora você tem um arquivo .htaccess operacional que pode ser usado para controlar as regras de roteamento da aplicação web. No próximo passo, criaremos um arquivo de exemplo de site que usaremos para demonstrar as regras de reescrita.

      Passo 3 — Configurando as Reescritas de URL

      Aqui, configuraremos uma reescrita básica de URL que converte URLs bonitas em caminhos reais para páginas. Especificamente, permitiremos aos usuários acessar http://ip_do_seu_servidor/about e exibir uma página chamada about.html.

      Comece criando um arquivo chamado about.html no web root:

      • sudo nano /var/www/html/about.html

      Copie o seguinte código HTML no arquivo, salve e feche-o.

      /var/www/html/about.html

      <html>
          <head>
              <title>About Us</title>
          </head>
          <body>
              <h1>About Us</h1>
          </body>
      </html>
      

      Você pode acessar esta página em http://ip_do_seu_servidor/about.html, mas observe que, se tentar acessar http://ip_do_seu_servidor/about, você verá um erro 404 Not Found. Para acessar a página usando /about, criaremos uma regra de reescrita.

      Todas as regras de reescrita ou RewriteRules seguem este formato:

      General RewriteRule structure

      RewriteRule pattern substitution [flags]
      
      • RewriteRule especifica a diretiva.
      • pattern é uma expressão regular que corresponde à string desejada da URL, que é o que o usuário digita no navegador.
      • substitution é o caminho para a URL real, ou seja, o caminho do arquivo que o Apache vai servir.
      • flags são parâmetros opcionais que podem modificar o funcionamento da regra.

      Vamos criar nossa regra de reescrita de URL. Abra o arquivo .htaccess:

      • sudo nano /var/www/html/.htaccess

      Após a primeira linha, adicione o seguinte RewriteRule e salve o arquivo:

      /var/www/html/.htaccess

      RewriteEngine on
      RewriteRule ^about$ about.html [NC]
      

      Nesse caso, ^about$ é a string desejada, about.html é a substituição e [NC] é uma flag. Nosso exemplo usa alguns caracteres com significado especial:

      • ^ indica o início da URL, após ip_do_seu_servidor/.
      • $ indica o final da URL.
      • about busca correspondência com a string “about”.
      • about.html é o arquivo real que o usuário acessa.
      • [NC] é a flag que torna a regra insensível a maiúsculas e minúsculas.

      Agora você pode acessar http://ip_do_seu_servidor/about no seu navegador. De fato, com a regra mostrada acima, as seguintes URLs também apontarão para about.html:

      • http://ip_do_seu_servidor/about, por causa da definição da regra.
      • http://ip_do_seu_servidor/About, porque a regra não diferencia maiúsculas de minúsculas.
      • http://ip_do_seu_servidor/about.html, porque o nome do arquivo original sempre funcionará.

      No entanto, o seguinte não funcionará:

      • http://ip_do_seu_servidor/about/, porque a regra declara explicitamente que não pode haver nada após about, pois o caracter $ aparece após about.
      • http://ip_do_seu_servidor/contact, porque isso não vai conicidir com a string about na regra.

      Agora você tem um arquivo .htaccess operacional com uma regra básica que pode ser modificada e ampliada para suas necessidades. Nas seções a seguir, mostraremos dois exemplos adicionais de diretivas usadas com freqüência.

      As aplicações web geralmente usam strings de consulta ou query strings, que são adicionadas a uma URL usando um ponto de interrogação (?) após o endereço. Parâmetros separados são delimitados usando um E comercial (&). As query strings podem ser usadas para transmitir dados adicionais entre páginas individuais de aplicações.

      Por exemplo, uma página de resultados de pesquisa escrita em PHP pode usar uma URL como http://example.com/results.php?item=shirt&season=summer. Neste exemplo, dois parâmetros adicionais são passados para o script de aplicação imaginário results.php: item, com o valor shirt, e season com o valor summer. A aplicação pode usar as informações da query string para criar a página certa para o visitante.

      As regras de reescrita do Apache geralmente são empregadas para simplificar links longos e desagradáveis, como o exemplo acima, em URLs amigáveis ou friendly URLs que são mais fáceis de digitar e interpretar visualmente. Neste exemplo, gostaríamos de simplificar o link acima para se tornar http://example.com/shirt/summer. Os valores dos parâmetros shirt e summer ainda estão no endereço, mas sem a query string e o nome do script.

      Aqui está uma regra para implementar isso:

      Simple substition

      RewriteRule ^shirt/summer$ results.php?item=shirt&season=summer [QSA]
      

      O shirt/summer é explicitamente correspondido no endereço solicitado e o Apache é instruído a servir results.php?item=shirt&season=summer no lugar.

      As flags [QSA] são comumente usadas em regras de reescrita. Eles dizem ao Apache para anexar qualquer query string adicional à URL servida, portanto, se o visitante digitar http://example.com/shirt/summer?page=2 o servidor irá responder com results.php?item=shirt&season=summer&page=2. Sem ela, a query string adicional seria descartada.

      Embora esse método atinja o efeito desejado, o nome do item e a estação são codificados fisicamente na regra. Isso significa que a regra não funcionará para outros itens, como pants, ou para outras estações, como winter.

      Para tornar a regra mais genérica, podemos usar expressões regulares para combinar partes do endereço original e usá-las em um padrão de substituição. A regra modificada ficará assim:

      Simple substition

      RewriteRule ^([A-Za-z0-9]+)/(summer|winter|fall|spring) results.php?item=$1&season=$2 [QSA]
      

      O primeiro grupo de expressões regulares entre parênteses corresponde a uma string contendo caracteres alfanuméricos e números como shirt ou pants e salva o fragmento correspondente como a variável $1. O segundo grupo de expressões regulares entre parênteses faz a correspondência exata de summer, winter, fall, ou spring, e, da mesma forma, salva o fragmento correspondente como $2.

      Os fragmentos que correspondem são então usados na URL resultante nas variáveis item e season, em vez dos valores shirt e summer fisicamente codificados que usamos anteriormente.

      O que foi apresentado acima irá converter, por exemplo, http://example.com/pants/summer para http://example.com/results.php?item=pants&season=summer. Este exemplo também não fica obsoleto, permitindo que vários itens e estações sejam reescritos corretamente usando uma única regra.

      As regras de reescrita nem sempre são avaliadas uma a uma, sem limitações. A diretiva RewriteCond nos permite adicionar condições às nossas regras de reescrita para controlar quando as regras serão processadas. Todos os RewriteConds seguem o seguinte formato:

      General RewriteCond structure

      RewriteCond TestString Condition [Flags]
      
      • RewriteCond especifica a diretiva RewriteCond.
      • TestString é a string a ser testada.
      • Condition é o padrão ou a condição a ser correspondida.
      • Flags são parâmetros opcionais que podem modificar as condições e as regras de avaliação.

      Se um RewriteCond for avaliado como verdadeiro, a próxima RewriteRule será considerada. Caso contrário, a regra será descartada. Múltiplos RewriteConds podem ser usados um após o outro, embora todos devam ser avaliados como verdadeiros para que a próxima regra seja considerada.

      Como exemplo, suponha que você gostaria de redirecionar todas as solicitações para arquivos ou diretórios inexistentes no seu site de volta à página inicial, em vez de mostrar a página de erro padrão 404 Not Found. Isso pode ser conseguido com as seguintes regras condicionais:

      Redirect all requests to non-existent files and directories to home page

      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /
      

      Com o exposto acima:

      • %{REQUEST_FILENAME} é a string a ser verificada. Nesse caso, é o nome do arquivo solicitado, que é uma variável do sistema disponível para cada solicitação.
      • -f é uma condição interna que verifica se o nome solicitado existe no disco e é um arquivo. O ! é um operador de negação. Combinado, !-f é avaliado como verdadeiro apenas se o nome especificado não existir ou não for um arquivo.
      • De maneira similar, !-d é avaliado como verdadeiro somente se o nome especificado não existir ou não for um diretório.

      O RewriteRule na linha final entrará em vigor apenas para solicitações de arquivos ou diretórios inexistentes. O RewriteRule em si é muito simples e redireciona todas as solicitações para a raiz do site /.

      O mod_rewrite lhe permite criar URLs amigáveis e legíveis por humanos. Neste tutorial, você aprendeu como usar a diretiva RewriteRule para redirecionar URLs, incluindo aquelas com query strings. Você também aprendeu como redirecionar condicionalmente URLs usando a diretiva RewriteCond.

      Se você quiser saber mais sobre o mod_rewrite, dê uma olhada em Apache’s mod_rewrite Introduction e Apache’s official documentation for mod_rewrite.



      Source link

      How To Rewrite URLs with mod_rewrite for Apache on Debian 10


      Introduction

      Apache’s mod_rewrite module lets you rewrite URLs in a cleaner fashion, translating human-readable paths into code-friendly query strings. It also lets you rewrite URLs based on conditions.

      An .htaccess file lets you create and apply rewrite rules without accessing server configuration files. By placing the .htaccess file in the root of your web site, you can manage rewrites on a per-site or per-directory basis.

      In this tutorial, you’ll enable mod_rewrite and use .htaccess files to create a basic URL redirection, and then explore a couple of advanced use cases.

      Prerequisites

      To follow this tutorial, you will need:

      Step 1 — Enabling mod_rewrite

      In order for Apache to understand rewrite rules, we first need to activate mod_rewrite. It’s already installed, but it’s disabled on a default Apache installation. Use the a2enmod command to enable the module:

      This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache:

      • sudo systemctl restart apache2

      mod_rewrite is now fully enabled. In the next step we will set up an .htaccess file that we’ll use to define rewrite rules for redirects.

      Step 2 — Setting Up .htaccess

      An .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web application’s security. The period that precedes the filename ensures that the file is hidden.

      Note: Any rules that you can put in an .htaccess file can also be put directly into server configuration files. In fact, the official Apache documentation recommends using server configuration files instead of .htaccess thanks to faster processing times.

      However, in this simple example, the performance increase will be negligible. Additionally, setting rules in .htaccess is convenient, especially with multiple websites on the same server. It does not require a server restart for changes to take effect or root privileges to edit rules, simplifying maintenance and the process of making changes with an unprivileged account. Popular open-source software like WordPress and Joomla rely on .htaccess files to make modifications and additional rules on demand.

      Before you start using .htaccess files, you’ll need to set up and secure a few more settings.

      By default, Apache prohibits using an .htaccess file to apply rewrite rules, so first you need to allow changes to the file. Open the default Apache configuration file using nano or your favorite text editor:

      • sudo nano /etc/apache2/sites-available/000-default.conf

      Inside that file, you will find a <VirtualHost *:80> block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented:

      /etc/apache2/sites-available/000-default.conf

      <VirtualHost *:80>
          <Directory /var/www/html>
              Options Indexes FollowSymLinks
              AllowOverride All
              Require all granted
          </Directory>
      
          . . .
      </VirtualHost>
      

      Save and close the file. If you used nano, do so by pressing CTRL+X, Y, then ENTER.

      Then, check your configuration:

      • sudo apache2ctl configtest

      If there are no errors, restart Apache to put your changes into effect:

      • sudo systemctl restart apache2

      Now, create an .htaccess file in the web root:

      • sudo nano /var/www/html/.htaccess

      Add this line at the top of the new file to activate the rewrite engine.

      /var/www/html/.htaccess

      RewriteEngine on
      

      Save the file and exit.

      You now have an operational .htaccess file that you can use to govern your web application’s routing rules. In the next step, we will create a sample website file that we’ll use to demonstrate rewrite rules.

      Step 3 — Configuring URL Rewrites

      Here, we will set up a basic URL rewrite which converts pretty URLs into actual paths to pages. Specifically, we will allow users to access http://your_server_ip/about, and display a page called about.html.

      Begin by creating a file named about.html in the web root:

      • sudo nano /var/www/html/about.html

      Copy the following HTML code into the file, then save and close it.

      /var/www/html/about.html

      <html>
          <head>
              <title>About Us</title>
          </head>
          <body>
              <h1>About Us</h1>
          </body>
      </html>
      

      You can access this page at http://your_server_ip/about.html, but notice that if you try to access http://your_server_ip/about, you will see a 404 Not Found error. To access the page using /about instead, we’ll create a rewrite rule.

      All RewriteRules follow this format:

      General RewriteRule structure

      RewriteRule pattern substitution [flags]
      
      • RewriteRule specifies the directive.
      • pattern is a regular expression that matches the desired string from the URL, which is what the viewer types in the browser.
      • substitution is the path to the actual URL, i.e. the path of the file Apache serves.
      • flags are optional parameters that can modify how the rule works.

      Let’s create our URL rewrite rule. Open up the .htaccess file:

      • sudo nano /var/www/html/.htaccess

      After the first line, add the following RewriteRule and save the file:

      /var/www/html/.htaccess

      RewriteEngine on
      RewriteRule ^about$ about.html [NC]
      

      In this case, ^about$ is the pattern, about.html is the substitution, and [NC] is a flag. Our example uses a few characters with special meaning:

      • ^ indicates the start of the URL, after your_server_ip/.
      • $ indicates the end of the URL.
      • about matches the string “about”.
      • about.html is the actual file that the user accesses.
      • [NC] is a flag that makes the rule case insensitive.

      You can now access http://your_server_ip/about in your browser. In fact, with the rule shown above, the following URLs will also point to about.html:

      • http://your_server_ip/about, because of the rule definition.
      • http://your_server_ip/About, because the rule is case insensitive.
      • http://your_server_ip/about.html, because the original filename will always work.

      However, the following will not work:

      • http://your_server_ip/about/, because the rule explicitly states that there may be nothing after about, since the $ character appears after about.
      • http://your_server_ip/contact, because it won’t match the about string in the rule.

      You now have an operational .htaccess file with a basic rule that you can modify and extend to your needs. In the following sections, we will show two additional examples of commonly used directives.

      Example 1 — Simplifying Query Strings with RewriteRule

      Web applications often make use of query strings, which are appended to a URL using a question mark (?) after the address. Separate parameters are delimited using an ampersand (&). Query strings may be used for passing additional data between individual application pages.

      For example, a search result page written in PHP may use a URL like http://example.com/results.php?item=shirt&season=summer. In this example, two additional parameters are passed to the imaginary result.php application script: item, with the value shirt, and season with the value summer. The application may use the query string information to build the right page for the visitor.

      Apache rewrite rules are often employed to simplify such long and unpleasant links as the example above into friendly URLs that are easier to type and interpret visually. In this example, we would like to simplify the above link to become http://example.com/shirt/summer. The shirt and summer parameter values are still in the address, but without the query string and script name.

      Here’s one rule to implement this:

      Simple substition

      RewriteRule ^shirt/summer$ results.php?item=shirt&season=summer [QSA]
      

      The shirt/summer is explicitly matched in the requested address and Apache is told to serve results.php?item=shirt&season=summer instead.

      The [QSA] flags are commonly used in rewrite rules. They tell Apache to append any additional query string to the served URL, so if the visitor types http://example.com/shirt/summer?page=2 the server will respond with results.php?item=shirt&season=summer&page=2. Without it, the additional query string would get discarded.

      While this method achieves the desired effect, both the item name and season are hardcoded into the rule. This means the rule will not work for any other items, like pants, or seasons, like winter.

      To make the rule more generic, we can use regular expressions to match parts of the original address and use those parts in a substitution pattern. The modified rule will then look like this:

      Simple substition

      RewriteRule ^([A-Za-z0-9]+)/(summer|winter|fall|spring) results.php?item=$1&season=$2 [QSA]
      

      The first regular expression group in parenthesis matches a string containing alphanumeric characters and numbers like shirt or pants and saves the matched fragment as the $1 variable. The second regular expression group in parentheses matches exactly summer, winter, fall, or spring, and similarly saves the matched fragment as $2.

      The matched fragments are then used in the resulting URL in item and season variables instead of the hardcoded shirt and summer values we used before.

      The above will convert, for example, http://example.com/pants/summer into http://example.com/results.php?item=pants&season=summer. This example is also future proof, allowing multiple items and seasons to be correctly rewritten using a single rule.

      Example 2 — Adding Conditions with Logic Using RewriteConds

      Rewrite rules are not necessarily always evaluated one by one without any limitations. The RewriteCond directive lets us add conditions to our rewrite rules to control when the rules will be processed. All RewriteConds abide by the following format:

      General RewriteCond structure

      RewriteCond TestString Condition [Flags]
      
      • RewriteCond specifies the RewriteCond directive.
      • TestString is the string to test against.
      • Condition is the pattern or condition to match.
      • Flags are optional parameters that may modify the condition and evaluation rules.

      If a RewriteCond evaluates to true, the next RewriteRule will be considered. If it doesn’t, the rule will be discarded. Multiple RewriteConds may be used one after another, though all must evaluate to true for the next rule to be considered.

      As an example, let’s assume you would like to redirect all requests to non-existent files or directories on your site back to the home page instead of showing the standard 404 Not Found error page. This can be achieved with following conditions rules:

      Redirect all requests to non-existent files and directories to home page

      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule . /
      

      With the above:

      • %{REQUEST_FILENAME} is the string to check. In this case, it’s the requested filename, which is a system variable available for every request.
      • -f is a built-in condition which verifies if the requested name exists on disk and is a file. The ! is a negation operator. Combined, !-f evaluates to true only if the specified name does not exist or is not a file.
      • Similarly, !-d evaluates to true only if the specified name does not exist or is not a directory.

      The RewriteRule on the final line will come into effect only for requests to non-existent files or directories. The RewriteRule itself is very simple and redirects every request to the / website root.

      mod_rewrite lets you create human-readable URLs. In this tutorial, you learned how to use the RewriteRule directive to redirect URLs, including ones with query strings. You also learned how to conditionally redirect URLs using the RewriteCond directive.

      If you’d like to learn more about mod_rewrite, take a look at Apache’s mod_rewrite Introduction and Apache’s official documentation for mod_rewrite.



      Source link