One place for hosting & domains

      Apache

      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

      Como Instalar o Servidor Web Apache no CentOS 7


      Introdução

      O servidor HTTP Apache é o servidor web mais utilizado no mundo. Ele fornece muitos recursos poderosos incluindo módulos dinamicamente carregáveis, suporte robusto a mídia, e integração extensiva com outros softwares populares.

      Neste guia, você instalará um servidor web Apache com virtual hosts em seu servidor CentOS 7.

      Pré-requisitos

      Você precisará do seguinte para concluir este guia:

      Passo 1 — Instalando o Apache

      O Apache está disponível nos repositórios de software padrão do CentOS, o que significa que você pode instalá-lo com o gerenciador de pacotes yum.

      Agindo como o usuário não-root, com privilégios sudo configurado nos pré-requisitos, atualize o índice de pacotes local httpd do Apache para refletir as alterações mais recentes do upstream:

      Depois que os pacotes forem atualizados, instale o pacote Apache:

      Após confirmar a instalação, o yum instalará o Apache e todas as dependências necessárias. Quando a instalação estiver concluída, você estará pronto para iniciar o serviço.

      Passo 2 — Verificando seu Servidor Web

      O Apache não inicia automaticamente no CentOS depois que a instalação é concluída. Você precisará iniciar o processo do Apache manualmente:

      • sudo systemctl start httpd

      Verifique se o serviço está sendo executado com o seguinte comando:

      • sudo systemctl status httpd

      Você verá um status active quando o serviço estiver em execução:

      Output

      Redirecting to /bin/systemctl status httpd.service ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled) Active: active (running) since Wed 2019-02-20 01:29:08 UTC; 5s ago Docs: man:httpd(8) man:apachectl(8) Main PID: 1290 (httpd) Status: "Processing requests..." CGroup: /system.slice/httpd.service ├─1290 /usr/sbin/httpd -DFOREGROUND ├─1291 /usr/sbin/httpd -DFOREGROUND ├─1292 /usr/sbin/httpd -DFOREGROUND ├─1293 /usr/sbin/httpd -DFOREGROUND ├─1294 /usr/sbin/httpd -DFOREGROUND └─1295 /usr/sbin/httpd -DFOREGROUND ...

      Como você pode ver nesta saída, o serviço parece ter sido iniciado com sucesso. No entanto, a melhor maneira de testar isso é solicitar uma página do Apache.

      Você pode acessar a página inicial padrão do Apache para confirmar que o software está sendo executado corretamente através do seu endereço IP. Se você não souber o endereço IP do seu servidor, poderá obtê-lo de algumas maneiras diferentes a partir da linha de comando.

      Digite isto no prompt de comando do seu servidor:

      Esse comando exibirá todos os endereços de rede do host, assim você receberá um retorno com alguns endereços IP separados por espaços. Você pode experimentar cada um em seu navegador para ver se eles funcionam.

      Alternativamente, você pode usar o curl para solicitar seu IP através do icanhazip.com, que lhe dará seu endereço IPv4 público como visto de outro local na internet:

      Quando você tiver o endereço IP do seu servidor, insira-o na barra de endereços do seu navegador:

      http://ip_do_seu_servidor
      

      Você verá a página padrão do Apache do CentOS 7:

      Default Apache page for CentOS 7

      Esta página indica que o Apache está funcionando corretamente. Ela também inclui algumas informações básicas sobre arquivos importantes do Apache e sobre localizações de diretórios. Agora que o serviço está instalado e em execução, você pode usar diferentes comandos systemctl para gerenciar o serviço.

      Passo 3 — Gerenciando o Processo do Apache

      Agora que você tem seu servidor web funcionando, vamos passar por alguns comandos básicos de gerenciamento.

      Para parar seu servidor web, digite:

      • sudo systemctl stop httpd

      Para iniciar o servidor web quando ele estiver parado, digite:

      • sudo systemctl start httpd

      Para parar e iniciar o serviço novamente, digite:

      • sudo systemctl restart httpd

      Se você estiver simplesmente fazendo alterações de configuração, o Apache pode muita vezes recarregar sem perder conexões. Para fazer isso, use este comando:

      • sudo systemctl reload httpd

      Por padrão, o Apache é configurado para iniciar automaticamente quando o servidor é inicializado. Se isso não é o que você deseja, desabilite esse comportamento digitando:

      • sudo systemctl disable httpd

      Para reativar o serviço para iniciar na inicialização, digite:

      • sudo systemctl enable httpd

      O Apache agora será iniciado automaticamente quando o servidor inicializar novamente.

      A configuração padrão do Apache permitirá que seu servidor hospede um único site. Se você planeja hospedar vários domínios em seu servidor, precisará configurar virtual hosts em seu servidor Apache.

      Passo 4 — Configurando Virtual Hosts (Recomendado)

      Ao utilizar o servidor web Apache, você pode usar virtual hosts (similares aos blocos do servidor no Nginx) para encapsular detalhes de configuração e hospedar mais de um domínio a partir de um único servidor. Neste passo você irá configurar um domínio chamado example.com, mas você deve substituí-lo por seu próprio nome de domínio. Para aprender mais sobre a configuração de um nome de domínio com a DigitalOcean, veja nossa Introdução ao DNS da DigitalOcean.

      O Apache no CentOS 7 tem um bloco de servidor ativado por padrão que é configurado para servir documentos a partir do diretório /var/www/html. Apesar disso funcionar bem para um único site, pode ficar difícil se você estiver hospedando vários sites. Em vez de modificar /var/www/html, você irá criar uma estrutura de diretórios dentro de /var/www para o site example.com, deixando /var/www/html no lugar como o diretório padrão a ser servido se uma requisição de cliente não corresponder a nenhum outro site.

      Crie o diretório html para example.com como segue, usando a flag -p para criar qualquer diretório pai que for necessário:

      • sudo mkdir -p /var/www/example.com/html

      Crie um diretório adicional para armazenar arquivos de log para o site:

      • sudo mkdir -p /var/www/example.com/log

      Em seguida, atribua a propriedade do diretório html com a variável de ambiente $USER:

      • sudo chown -R $USER:$USER /var/www/example.com/html

      Certifique-se de que seu web root ou pasta raiz para web tenha o conjunto de permissões padrão:

      • sudo chmod -R 755 /var/www

      Em seguida, crie uma página de exemplo index.html usando o vi ou seu editor favorito:

      • sudo vi /var/www/example.com/html/index.html

      Pressione i para alternar para o modo INSERT e adicione o seguinte exemplo de HTML ao arquivo:

      /var/www/example.com/html/index.html

      <html>
        <head>
          <title>Welcome to Example.com!</title>
        </head>
        <body>
          <h1>Success! The example.com virtual host is working!</h1>
        </body>
      </html>
      

      Salve e feche o arquivo pressionando ESC, digitando :wq e pressionando ENTER.

      Com o diretório do seu site e o arquivo de index de exemplo no lugar, você está quase pronto para criar os arquivos do virtual host. Os arquivos do virtual host especificam a configuração de seus sites independentes e informam ao servidor Apache como responder a várias solicitações de domínio.

      Antes de criar seus virtual hosts, você precisará criar um diretório sites-available para armazená-los. Você também criará o diretório sites-enabled que informa ao Apache que um virtual host está pronto para servir aos visitantes. O diretório sites-enabled conterá links simbólicos para os virtual hosts que queremos publicar. Crie ambos os diretórios com o seguinte comando:

      • sudo mkdir /etc/httpd/sites-available /etc/httpd/sites-enabled

      Em seguida, você dirá ao Apache para procurar por virtual hosts no diretório sites-enabled. Para fazer isso, edite o arquivo de configuração principal do Apache e adicione uma linha declarando um diretório opcional para arquivos de configuração adicionais:

      • sudo vi /etc/httpd/conf/httpd.conf

      Adicione esta linha ao final do arquivo:

      IncludeOptional sites-enabled/*.conf
      

      Salve e feche o arquivo quando terminar de adicionar essa linha. Agora que você tem seus diretórios de virtual host no lugar, você criará seu arquivo de virtual host.

      Comece criando um novo arquivo no diretório sites-available:

      • sudo vi /etc/httpd/sites-available/example.com.conf

      Adicione o seguinte bloco de configuração e altere o domínio example.com para o seu nome de domínio:

      /etc/httpd/sites-available/example.com.conf

      <VirtualHost *:80>
          ServerName www.example.com
          ServerAlias example.com
          DocumentRoot /var/www/example.com/html
          ErrorLog /var/www/example.com/log/error.log
          CustomLog /var/www/example.com/log/requests.log combined
      </VirtualHost>
      

      Isso dirá ao Apache onde encontrar diretamente a raiz que contém os documentos web publicamente acessíveis. Ele também informa ao Apache onde armazenar logs de erros e de solicitações para esse site específico.

      Salve e feche o arquivo quando terminar.

      Agora que você criou os arquivos do virtual host, você os habilitará para que o Apache saiba como servi-los aos visitantes. Para fazer isso, crie um link simbólico para cada virtual host no diretório sites-enabled:

      • sudo ln -s /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-enabled/example.com.conf

      Seu virtual host agora está configurado e pronto para servir conteúdo. Antes de reiniciar o serviço Apache, vamos garantir que o SELinux tenha as políticas corretas em vigor para seus virtual hosts.

      Passo 5 — Ajustando Permissões do SELinux para Virtual Hosts (Recomendado)

      O SELinux está configurado para funcionar com a configuração padrão do Apache. Como você configurou um diretório de log personalizado no arquivo de configuração de virtual hosts, você receberá um erro se tentar iniciar o serviço Apache. Para resolver isso, você precisa atualizar as políticas do SELinux para permitir que o Apache grave nos arquivos necessários. O SELinux traz maior segurança ao seu ambiente CentOS 7, portanto, não é recomendado desativar completamente o módulo do kernel.

      Existem diferentes maneiras de definir políticas com base nas necessidades do seu ambiente, pois o SELinux permite que você personalize seu nível de segurança. Esta etapa abordará dois métodos de ajuste das políticas do Apache: universalmente e em um diretório específico. Ajustar políticas em diretórios é mais seguro e, portanto, é a abordagem recomendada.

      Ajustando Políticas do Apache Universalmente

      Definir a política do Apache universalmente dirá ao SELinux para tratar todos os processos do Apache de forma idêntica usando o booleano httpd_unified. Embora essa abordagem seja mais conveniente, ela não fornecerá o mesmo nível de controle que uma abordagem centrada em uma diretiva de arquivo ou diretório.

      Execute o seguinte comando para definir uma política universal para o Apache:

      • sudo setsebool -P httpd_unified 1

      O comando setsebool altera os valores booleanos do SELinux. A flag -P atualizará o valor de tempo de inicialização, fazendo com que essa mudança persista durante as reinicializações. httpd_unified é o booleano que irá dizer ao SELinux para tratar todos os processos do Apache como do mesmo tipo, então você habilitou-o com um valor de 1.

      Ajustando as Políticas do Apache em um Diretório

      Configurar individualmente as permissões do SELinux para o diretório /var/www/example.com/log lhe dará mais controle sobre suas políticas do Apache, mas também pode exigir mais manutenção. Como essa opção não está definindo políticas universalmente, você precisará definir manualmente o tipo de contexto para todos os novos diretórios de log especificados em suas configurações de virtual host.

      Primeiro, verifique o tipo de contexto que o SELinux deu ao diretório /var/www/example.com/log:

      • sudo ls -dZ /var/www/example.com/log/

      Este comando lista e imprime o contexto do SELinux do diretório. Você verá uma saída semelhante à seguinte:

      Output

      drwxr-xr-x. root root unconfined_u:object_r:httpd_sys_content_t:s0 /var/www/example.com/log/

      O contexto atual é httpd_sys_content_t, que informa ao SELinux que o processo do Apache só pode ler arquivos criados neste diretório. Neste tutorial, você irá alterar o tipo de contexto do diretório /var/www/example.com/log para httpd_log_t. Esse tipo permitirá ao Apache gerar e agregar arquivos de log da aplicação web:

      • sudo semanage fcontext -a -t httpd_log_t "/var/www/example.com/log(/.*)?"

      Em seguida, use o comando restorecon para aplicar essas mudanças e fazer com que elas persistam durante as reinicializações:

      • sudo restorecon -R -v /var/www/example.com/log

      A flag -R executa este comando recursivamente, o que significa que ele atualizará quaisquer arquivos existentes para usar o novo contexto. A flag -v imprimirá as mudanças de contexto feitas pelo comando. Você verá a seguinte saída confirmando as alterações:

      Output

      restorecon reset /var/www/example.com/log context unconfined_u:object_r:httpd_sys_content_t:s0->unconfined_u:object_r:httpd_log_t:s0

      Você pode listar os contextos mais uma vez para ver as alterações:

      • sudo ls -dZ /var/www/example.com/log/

      A saída reflete o tipo de contexto atualizado:

      Output

      drwxr-xr-x. root root unconfined_u:object_r:httpd_log_t:s0 /var/www/example.com/log

      Agora que o diretório /var/www/example.com/log está usando o tipo httpd_log_t, você está pronto para testar sua configuração de virtual host.

      Passo 6 — Testando o Virtual Host (Recomendado)

      Uma vez que o contexto do SELinux tenha sido atualizado com quaisquer dos métodos, o Apache poderá gravar no diretório /var/www/example.com/log. Agora você pode reiniciar o serviço Apache com sucesso:

      • sudo systemctl restart httpd

      Liste o conteúdo do diretório /var/www/example.com/log para ver se o Apache criou os arquivos de log:

      • ls -lZ /var/www/example.com/log

      Você verá que o Apache foi capaz de criar os arquivos error.log e requests.log especificados na configuração do virtual host:

      Output

      -rw-r--r--. 1 root root 0 Feb 26 22:54 error.log -rw-r--r--. 1 root root 0 Feb 26 22:54 requests.log

      Agora que você tem seu virtual host configurado e as permissões do SELinux atualizadas, o Apache agora servirá seu nome de domínio. Você pode testar isso navegando até http://example.com, onde você deve ver algo assim:

      Success! The example.com virtual host is working!

      Isso confirma que seu virtual host foi configurado e está servindo o conteúdo com êxito. Repita os Passos 4 e 5 para criar novos virtual hosts com permissões do SELinux para domínios adicionais.

      Conclusão

      Neste tutorial, você instalou e gerenciou o servidor web Apache. Agora que você tem seu servidor web instalado, você tem muitas opções para o tipo de conteúdo que você pode servir e as tecnologias que você pode usar para criar uma experiência mais rica.

      Se você quiser criar uma pilha ou stack de aplicação mais completa, consulte este artigo sobre como configurar uma pilha LAMP no CentOS 7.



      Source link

      How To Create a Self-Signed SSL Certificate for Apache in Debian 10


      Introduction

      TLS, or transport layer security, and its predecessor SSL, which stands for secure sockets layer, are web protocols used to wrap normal traffic in a protected, encrypted wrapper.

      Using this technology, servers can send traffic safely between servers and clients without the possibility of messages being intercepted by outside parties. The certificate system also assists users in verifying the identity of the sites that they are connecting with.

      In this guide, we will show you how to set up a self-signed SSL certificate for use with an Apache web server on Debian 10.

      Note: A self-signed certificate will encrypt communication between your server and any clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers, users cannot use the certificate to validate the identity of your server automatically.

      A self-signed certificate may be appropriate if you do not have a domain name associated with your server and for instances where an encrypted web interface is not user-facing. If you do have a domain name, in many cases it is better to use a CA-signed certificate. You can find out how to set up a free trusted certificate with the Let’s Encrypt project here.

      Prerequisites

      Before you begin, you should have a non-root user configured with sudo privileges. You can learn how to set up such a user account by following our Initial Server Setup with Debian 10.

      You will also need to have the Apache web server installed. If you would like to install an entire LAMP (Linux, Apache, MariaDB, PHP) stack on your server, you can follow our guide on setting up LAMP on Debian 10. If you just want the Apache web server, skip the steps pertaining to PHP and MariaDB.

      When you have completed these prerequisites, continue below.

      Step 1 — Creating the SSL Certificate

      TLS/SSL works by using a combination of a public certificate and a private key. The SSL key is kept secret on the server. It is used to encrypt content sent to clients. The SSL certificate is publicly shared with anyone requesting the content. It can be used to decrypt the content signed by the associated SSL key.

      We can create a self-signed key and certificate pair with OpenSSL in a single command:

      • sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt

      You will be asked a series of questions. Before we go over that, let’s take a look at what is happening in the command we are issuing:

      • openssl: This is the basic command line tool for creating and managing OpenSSL certificates, keys, and other files.
      • req: This subcommand specifies that we want to use X.509 certificate signing request (CSR) management. The “X.509” is a public key infrastructure standard that SSL and TLS adheres to for its key and certificate management. We want to create a new X.509 cert, so we are using this subcommand.
      • -x509: This further modifies the previous subcommand by telling the utility that we want to make a self-signed certificate instead of generating a certificate signing request, as would normally happen.
      • -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Apache to be able to read the file, without user intervention, when the server starts up. A passphrase would prevent this from happening because we would have to enter it after every restart.
      • -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here.
      • -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
      • -keyout: This line tells OpenSSL where to place the generated private key file that we are creating.
      • -out: This tells OpenSSL where to place the certificate that we are creating.

      As we stated above, these options will create both a key file and a certificate. We will be asked a few questions about our server in order to embed the information correctly in the certificate.

      Fill out the prompts appropriately. The most important line is the one that requests the Common Name (e.g. server FQDN or YOUR name). You need to enter the domain name associated with your server or, more likely, your server’s public IP address.

      The entirety of the prompts will look something like this:

      Output

      Country Name (2 letter code) [AU]:US State or Province Name (full name) [Some-State]:New York Locality Name (eg, city) []:New York City Organization Name (eg, company) [Internet Widgits Pty Ltd]:Bouncy Castles, Inc. Organizational Unit Name (eg, section) []:Ministry of Water Slides Common Name (e.g. server FQDN or YOUR name) []:server_IP_address Email Address []:admin@your_domain.com

      Both of the files you created will be placed in the appropriate subdirectories under /etc/ssl.

      Step 2 — Configuring Apache to Use SSL

      We have created our key and certificate files under the /etc/ssl directory. Now we just need to modify our Apache configuration to take advantage of these.

      We will make a few adjustments to our configuration:

      1. We will create a configuration snippet to specify strong default SSL settings.
      2. We will modify the included SSL Apache Virtual Host file to point to our generated SSL certificates.
      3. (Recommended) We will modify the unencrypted Virtual Host file to automatically redirect requests to the encrypted Virtual Host.

      When we are finished, we should have a secure SSL configuration.

      Creating an Apache Configuration Snippet with Strong Encryption Settings

      First, we will create an Apache configuration snippet to define some SSL settings. This will set Apache up with a strong SSL cipher suite and enable some advanced features that will help keep our server secure. The parameters we will set can be used by any Virtual Hosts enabling SSL.

      Create a new snippet in the /etc/apache2/conf-available directory. We will name the file ssl-params.conf to make its purpose clear:

      • sudo nano /etc/apache2/conf-available/ssl-params.conf

      To set up Apache SSL securely, we will be using the recommendations by Remy van Elst on the Cipherli.st site. This site is designed to provide easy-to-consume encryption settings for popular software.

      The suggested settings on the site linked to above offer strong security. Sometimes, this comes at the cost of greater client compatibility. If you need to support older clients, there is an alternative list that can be accessed by clicking the link on the page labelled “Yes, give me a ciphersuite that works with legacy / old software.” That list can be substituted for the items copied below.

      The choice of which config you use will depend largely on what you need to support. They both will provide great security.

      For our purposes, we can copy the provided settings in their entirety. We will just make one small change to this and disable the Strict-Transport-Security header (HSTS).

      Preloading HSTS provides increased security, but can have far-reaching consequences if accidentally enabled or enabled incorrectly. In this guide, we will not enable the settings, but you can modify that if you are sure you understand the implications.

      Before deciding, take a moment to read up on HTTP Strict Transport Security, or HSTS, and specifically about the “preload” functionality.

      Paste the following configuration into the ssl-params.conf file we opened:

      /etc/apache2/conf-available/ssl-params.conf

      SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
      SSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
      SSLHonorCipherOrder On
      # Disable preloading HSTS for now.  You can use the commented out header line that includes
      # the "preload" directive if you understand the implications.
      # Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
      Header always set X-Frame-Options DENY
      Header always set X-Content-Type-Options nosniff
      # Requires Apache >= 2.4
      SSLCompression off
      SSLUseStapling on
      SSLStaplingCache "shmcb:logs/stapling-cache(150000)"
      # Requires Apache >= 2.4.11
      SSLSessionTickets Off
      

      Save and close the file when you are finished.

      Modifying the Default Apache SSL Virtual Host File

      Next, let’s modify /etc/apache2/sites-available/default-ssl.conf, the default Apache SSL Virtual Host file. If you are using a different server block file, substitute its name in the commands below.

      Before we go any further, let’s back up the original SSL Virtual Host file:

      • sudo cp /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-available/default-ssl.conf.bak

      Now, open the SSL Virtual Host file to make adjustments:

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

      Inside, with most of the comments removed, the Virtual Host block should look something like this by default:

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

      <IfModule mod_ssl.c>
              <VirtualHost _default_:443>
                      ServerAdmin webmaster@localhost
      
                      DocumentRoot /var/www/html
      
                      ErrorLog ${APACHE_LOG_DIR}/error.log
                      CustomLog ${APACHE_LOG_DIR}/access.log combined
      
                      SSLEngine on
      
                      SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
                      SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
      
                      <FilesMatch ".(cgi|shtml|phtml|php)$">
                                      SSLOptions +StdEnvVars
                      </FilesMatch>
                      <Directory /usr/lib/cgi-bin>
                                      SSLOptions +StdEnvVars
                      </Directory>
      
              </VirtualHost>
      </IfModule>
      

      We will be making some minor adjustments to the file. We will set the normal things we’d want to adjust in a Virtual Host file (ServerAdmin email address, ServerName, etc.), and adjust the SSL directives to point to our certificate and key files. Again, if you’re using a different document root, be sure to update the DocumentRoot directive.

      After making these changes, your server block should look similar to this:

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

      <IfModule mod_ssl.c>
              <VirtualHost _default_:443>
                      ServerAdmin your_email@example.com
                      ServerName server_domain_or_IP
      
                      DocumentRoot /var/www/html
      
                      ErrorLog ${APACHE_LOG_DIR}/error.log
                      CustomLog ${APACHE_LOG_DIR}/access.log combined
      
                      SSLEngine on
      
                      SSLCertificateFile      /etc/ssl/certs/apache-selfsigned.crt
                      SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
      
                      <FilesMatch ".(cgi|shtml|phtml|php)$">
                                      SSLOptions +StdEnvVars
                      </FilesMatch>
                      <Directory /usr/lib/cgi-bin>
                                      SSLOptions +StdEnvVars
                      </Directory>
      
              </VirtualHost>
      </IfModule>
      

      Save and close the file when you are finished.

      As it stands now, the server will provide both unencrypted HTTP and encrypted HTTPS traffic. For better security, it is recommended in most cases to redirect HTTP to HTTPS automatically. If you do not want or need this functionality, you can safely skip this section.

      To adjust the unencrypted Virtual Host file to redirect all traffic to be SSL encrypted, open the /etc/apache2/sites-available/000-default.conf file:

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

      Inside, within the VirtualHost configuration blocks, add a Redirect directive, pointing all traffic to the SSL version of the site:

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

      <VirtualHost *:80>
              . . .
      
              Redirect "/" "https://your_domain_or_IP/"
      
              . . .
      </VirtualHost>
      

      Save and close the file when you are finished.

      That’s all of the configuration changes you need to make to Apache. Next, we will discuss how to update firewall rules with ufw to allow encrypted HTTPS traffic to your server.

      Step 3 — Adjusting the Firewall

      If you have the ufw firewall enabled, as recommended by the prerequisite guides, you might need to adjust the settings to allow for SSL traffic. Fortunately, when installed on Debian 10, ufw comes loaded with app profiles which you can use to tweak your firewall settings

      We can see the available profiles by typing:

      You should see a list like this, with the following four profiles near the bottom of the output:

      Output

      Available applications: . . . WWW WWW Cache WWW Full WWW Secure . . .

      You can see the current setting by typing:

      If you allowed only regular HTTP traffic earlier, your output might look like this:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere WWW ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) WWW (v6) ALLOW Anywhere (v6)

      To additionally let in HTTPS traffic, allow the "WWW Full" profile and then delete the redundant "WWW" profile allowance:

      • sudo ufw allow 'WWW Full'
      • sudo ufw delete allow 'WWW'

      Your status should look like this now:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere WWW Full ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) WWW Full (v6) ALLOW Anywhere (v6)

      With your firewall configured to allow HTTPS traffic, you can move on to the next step where we’ll go over how to enable a few modules and configuration files to allow SSL to function properly.

      Step 4 — Enabling the Changes in Apache

      Now that we've made our changes and adjusted our firewall, we can enable the SSL and headers modules in Apache, enable our SSL-ready Virtual Host, and then restart Apache to put these changes into effect.

      Enable mod_ssl, the Apache SSL module, and mod_headers, which is needed by some of the settings in our SSL snippet, with the a2enmod command:

      • sudo a2enmod ssl
      • sudo a2enmod headers

      Next, enable your SSL Virtual Host with the a2ensite command:

      • sudo a2ensite default-ssl

      You will also need to enable your ssl-params.conf file, to read in the values you’ve set:

      At this point, the site and the necessary modules are enabled. We should check to make sure that there are no syntax errors in our files. Do this by typing:

      • sudo apache2ctl configtest

      If everything is successful, you will get a result that looks like this:

      Output

      Syntax OK

      As long as your output has Syntax OK in it, then your configuration file has no syntax errors and you can safely restart Apache to implement the changes:

      • sudo systemctl restart apache2

      With that, your self-signed SSL certificate is all set. You can now test that your server is correctly encrypting its traffic.

      Step 5 — Testing Encryption

      You’re now ready to test your SSL server.

      Open your web browser and type https:// followed by your server's domain name or IP into the address bar:

      https://server_domain_or_IP
      

      Because the certificate you created isn't signed by one of your browser's trusted certificate authorities, you will likely see a scary looking warning like the one below:

      Apache self-signed cert warning

      This is expected and normal. We are only interested in the encryption aspect of our certificate, not the third party validation of our host's authenticity. Click ADVANCED and then the link provided to proceed to your host anyways:

      Apache self-signed override

      You should be taken to your site. If you look in the browser address bar, you will see a lock with an "x" over it or another similar “not secure” notice. In this case, this just means that the certificate cannot be validated. It is still encrypting your connection.

      If you configured Apache to redirect HTTP to HTTPS, you can also check whether the redirect functions correctly:

      http://server_domain_or_IP
      

      If this results in the same icon, this means that your redirect worked correctly. However, the redirect you created earlier is only a temporary redirect. If you’d like to make the redirection to HTTPS permanent, continue on to the final step.

      Step 6 — Changing to a Permanent Redirect

      If your redirect worked correctly and you are sure you want to allow only encrypted traffic, you should modify the unencrypted Apache Virtual Host again to make the redirect permanent.

      Open your server block configuration file again:

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

      Find the Redirect line we added earlier. Add permanent to that line, which changes the redirect from a 302 temporary redirect to a 301 permanent redirect:

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

      <VirtualHost *:80>
              . . .
      
              Redirect permanent "/" "https://your_domain_or_IP/"
      
              . . .
      </VirtualHost>
      

      Save and close the file.

      Check your configuration for syntax errors:

      • sudo apache2ctl configtest

      If this command doesn’t report any syntax errors, restart Apache:

      • sudo systemctl restart apache2

      This will make the redirect permanent, and your site will only serve traffic over HTTPS.

      Conclusion

      You have configured your Apache server to use strong encryption for client connections. This will allow you serve requests securely, and will prevent outside parties from reading your traffic.



      Source link