One place for hosting & domains

      CentOS

      How To Create a Self-Signed SSL Certificate for Apache on CentOS 8


      Not using CentOS 8?


      Choose a different version or distribution.

      Introduction

      TLS, or “transport layer security” — and its predecessor SSL — are protocols used to wrap normal traffic in a protected, encrypted wrapper. Using this technology, servers can safely send information to their clients without their messages being intercepted or read by an outside party.

      In this guide, we will show you how to create and use a self-signed SSL certificate with the Apache web server on a CentOS 8 machine.

      Note: A self-signed certificate will encrypt communication between your server and its clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers and operating systems, users cannot use the certificate to automatically validate the identity of your server. As a result, your users will see a security error when visiting your site.

      Because of this limitation, self-signed certificates are not appropriate for a production environment serving the public. They are typically used for testing, or for securing non-critical services used by a single user or a small group of users that can establish trust in the certificate’s validity through alternate communication channels.

      For a more production-ready certificate solution, check out Let’s Encrypt, a free certificate authority. You can learn how to download and configure a Let’s Encrypt certificate in our How To Secure Apache with Let’s Encrypt on CentOS 8 tutorial.

      Prerequisites

      Before starting this tutorial, you’ll need the following:

      • Access to a CentOS 8 server with a non-root, sudo-enabled user. Our Initial Server Setup with CentOS 8 guide can show you how to create this account.
      • You will also need to have Apache installed. You can install Apache using dnf:

        Enable Apache and start it using systemctl:

        • sudo systemctl enable httpd
        • sudo systemctl start httpd

        And finally, if you have a firewalld firewall set up, open up the http and https ports:

        • sudo firewall-cmd --permanent --add-service=http
        • sudo firewall-cmd --permanent --add-service=https
        • sudo firewall-cmd --reload

      After these steps are complete, be sure you are logged in as your non-root user and continue with the tutorial.

      Step 1 — Installing mod_ssl

      We first need to install mod_ssl, an Apache module that provides support for SSL encryption.

      Install mod_ssl with the dnf command:

      Because of a packaging bug, we need to restart Apache once to properly generate the default SSL certificate and key, otherwise we’ll get an error reading '/etc/pki/tls/certs/localhost.crt' does not exist or is empty.

      • sudo systemctl restart httpd

      The mod_ssl module is now enabled and ready for use.

      Step 2 — Creating the SSL Certificate

      Now that Apache is ready to use encryption, we can move on to generating a new SSL certificate. The certificate will store some basic information about your site, and will be accompanied by a key file that allows the server to securely handle encrypted data.

      We can create the SSL key and certificate files with the openssl command:

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

      After you enter the command, you will be taken to a prompt where you can enter information about your website. Before we go over that, let’s take a look at what is happening in the command we are issuing:

      • openssl: This is the command line tool for creating and managing OpenSSL certificates, keys, and other files.
      • req -x509: This specifies that we want to use X.509 certificate signing request (CSR) management. X.509 is a public key infrastructure standard that SSL and TLS adhere to for key and certificate management.
      • -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, since 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. Many modern browsers will reject any certificates that are valid for longer than one year.
      • -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.

      Fill out the prompts appropriately. The most important line is the one that requests the Common Name. You need to enter either the hostname you’ll use to access the server by, or the public IP of the server. It’s important that this field matches whatever you’ll put into your browser’s address bar to access the site, as a mismatch will cause more security errors.

      The full list of prompts will look something like this:

      Country Name (2 letter code) [XX]:US
      State or Province Name (full name) []:Example
      Locality Name (eg, city) [Default City]:Example 
      Organization Name (eg, company) [Default Company Ltd]:Example Inc
      Organizational Unit Name (eg, section) []:Example Dept
      Common Name (eg, your name or your server's hostname) []:your_domain_or_ip
      Email Address []:webmaster@example.com
      

      Both of the files you created will be placed in the appropriate subdirectories of the /etc/pki/tls directory. This is a standard directory provided by CentOS for this purpose.

      Next we will update our Apache configuration to use the new certificate and key.

      Step 3 — Configuring Apache to Use SSL

      Now that we have our self-signed certificate and key available, we need to update our Apache configuration to use them. On CentOS, you can place new Apache configuration files (they must end in .conf) into /etc/httpd/conf.d and they will be loaded the next time the Apache process is reloaded or restarted.

      For this tutorial we will create a new minimal configuration file. If you already have an Apache <Virtualhost> set up and just need to add SSL to it, you will likely need to copy over the configuration lines that start with SSL, and switch the VirtualHost port from 80 to 443. We will take care of port 80 in the next step.

      Open a new file in the /etc/httpd/conf.d directory:

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

      Paste in the following minimal VirtualHost configuration:

      /etc/httpd/conf.d/your_domain_or_ip.conf

      <VirtualHost *:443>
          ServerName your_domain_or_ip
          DocumentRoot /var/www/ssl-test
          SSLEngine on
          SSLCertificateFile /etc/pki/tls/certs/apache-selfsigned.crt
          SSLCertificateKeyFile /etc/pki/tls/private/apache-selfsigned.key
      </VirtualHost>
      

      Be sure to update the ServerName line to however you intend to address your server. This can be a hostname, full domain name, or an IP address. Make sure whatever you choose matches the Common Name you chose when making the certificate.

      The remaining lines specify a DocumentRoot directory to serve files from, and the SSL options needed to point Apache to our newly-created certificate and key.

      Now let’s create our DocumentRoot and put an HTML file in it just for testing purposes:

      • sudo mkdir /var/www/ssl-test

      Open a new index.html file with your text editor:

      • sudo vi /var/www/ssl-test/index.html

      Paste the following into the blank file:

      /var/www/ssl-test/index.html

      <h1>it worked!</h1>
      

      This is not a full HTML file, of course, but browsers are lenient and it will be enough to verify our configuration.

      Save and close the file, then check your Apache configuration for syntax errors by typing:

      • sudo apachectl configtest

      You may see some warnings, but as long as the output ends with Syntax OK, you are safe to continue. If this is not part of your output, check the syntax of your files and try again.

      When all is well, reload Apache to pick up the configuration changes:

      • sudo systemctl reload httpd

      Now load your site in a browser, being sure to use https:// at the beginning.

      You should see an error. This is normal for a self-signed certificate! The browser is warning you that it can’t verify the identity of the server, because our certificate is not signed by any of the browser’s known certificate authorities. For testing purposes and personal use this can be fine. You should be able to click through to advanced or more information and choose to proceed.

      After you do so, your browser will load the it worked! message.

      Note: if your browser doesn’t connect at all to the server, make sure your connection isn’t being blocked by a firewall. If you are using firewalld, the following commands will open ports 80 and 443:

      • sudo firewall-cmd --permanent --add-service=http
      • sudo firewall-cmd --permanent --add-service=https
      • sudo firewall-cmd --reload

      Next we will add another VirtualHost section to our configuration to serve plain HTTP requests and redirect them to HTTPS.

      Step 4 — Redirecting HTTP to HTTPS

      Currently, our configuration will only respond to HTTPS requests on port 443. It is good practice to also respond on port 80, even if you want to force all traffic to be encrypted. Let’s set up a VirtualHost to respond to these unencrypted requests and redirect them to HTTPS.

      Open the same Apache configuration file we started in previous steps:

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

      At the bottom, create another VirtualHost block to match requests on port 80. Use the ServerName directive to again match your domain name or IP address. Then, use Redirect to match any requests and send them to the SSL VirtualHost. Make sure to include the trailing slash:

      /etc/httpd/conf.d/your_domain_or_ip.conf

      <VirtualHost *:80>
          ServerName your_domain_or_ip
          Redirect / https://your_domain_or_ip/
      </VirtualHost>
      

      Save and close this file when you are finished, then test your configuration syntax again, and reload Apache:

      • sudo apachectl configtest
      • sudo systemctl reload httpd

      You can test the new redirect functionality by visiting your site with plain http:// in front of the address. You should be redirected to https:// automatically.

      Conclusion

      You have now configured Apache to serve encrypted requests using a self-signed SSL certificate, and to redirect unecrypted HTTP requests to HTTPS.

      If you are planning on using SSL for a public website, you should look into purchasing a domain name and using a widely supported certificate authority such as Let’s Encrypt.

      For more information on using Let’s Encrypt with Apache, please read our How To Secure Apache with Let’s Encrypt on CentOS 8 tutorial.



      Source link

      How To Secure Apache with Let’s Encrypt on CentOS 8


      Not using CentOS 8?


      Choose a different version or distribution.

      Introduction

      Let’s Encrypt is a Certificate Authority (CA) that facilitates obtaining and installing free TLS/SSL certificates, thereby enabling encrypted HTTPS on web servers. It simplifies the process by working with clients, such as Certbot, to automate the necessary steps.

      In this tutorial, you will use Certbot to set up a TLS/SSL certificate with the Apache web server on CentOS 8. Additionally, you will automate the certificate renewal process using a cron job, which you can learn more about by reading How To Use Cron To Automate Tasks on CentOS 8.

      Prerequisites

      In order to complete this guide, you will need:

      • One CentOS 8 server with a non-root sudo-enabled user and a basic firewalld firewall set up by following the CentOS 8 initial server setup guide.
      • Apache installed on the server with a virtual host configured for your domain. You can learn how to set this up by following our tutorial How To Install the Apache Web Server on CentOS 8. Be sure that you have a virtual host set up for your domain. This tutorial will use /etc/httpd/sites-available/example.com.conf as an example.
      • You should own or control the registered domain name that you wish to use the certificate with. If you do not already have a registered domain name, you may purchase one on Namecheap, get one for free on Freenom, or use the domain registrar of your choice.
      • A DNS A Record that points your domain to the public IP address of your server. If you host your domain through DigitalOcean, you can refer to the DigitalOcean DNS documentation for details on how to add these records with the DigitalOcean platform. DNS A records are required because of how Let’s Encrypt validates that you own the domain it is issuing a certificate for. For example, if you want to obtain a certificate for example.com, that domain must resolve to your server for the validation process to work. Our setup will use example.com and www.example.com as the domain names, both of which will require a valid DNS record.

      When you have all of these prerequisites completed, move on to install the Certbot client software.

      Step 1 — Installing the Certbot Let’s Encrypt Client

      To use Let’s Encrypt to obtain an SSL certificate, you first need to install Certbot and mod_ssl, an Apache module that provides support for SSLv3 encryption.

      The certbot package is not available through the package manager by default. You will need to enable the EPEL repository to install Certbot.

      To add the CentOS 8 EPEL repository, run the following command:

      • sudo dnf install epel-release

      Now that you have access to the repository, install all of the required packages:

      • sudo dnf install certbot python3-certbot-apache mod_ssl

      With these services installed, you’re now ready to run Certbot and fetch your certificates.

      Step 2 — Obtaining a Certificate

      Now that Certbot is installed, you can use it to request an SSL certificate for your domain.

      Using the certbot Let’s Encrypt client to generate the SSL Certificate for Apache automates many of the steps in the process. The client will automatically obtain and install a new SSL certificate that is valid for the domains you provide as parameters.

      To execute the interactive installation and obtain a certificate that covers only a single domain, run the certbot command with:

      • sudo certbot --apache -d example.com

      This runs certbot with the --apache plugin and specifies the domain to configure the certificate for with the -d flag.

      If you want to install a single certificate that is valid for multiple domains or subdomains, you can pass them as additional parameters to the command, tagging each new domain or subdomain with the -d flag. The first domain name in the list of parameters will be the base domain used by Let’s Encrypt to create the certificate. For this reason, pass the base domain name as first in the list, followed by any additional subdomains or aliases:

      • sudo certbot --apache -d example.com -d www.example.com

      The base domain in this example is example.com.

      The certbot utility can also prompt you to choose a domain based on your existing Apache configuration. To use this functionality, call certbot without any domains specified:

      The program will present you with a step-by-step guide to customize your certificate options. It will ask you to provide an email address for lost key recovery and notices, and then prompt you to agree to the terms of service. If you did not specify your domains on the command line, you will be prompted for that as well. If your Virtual Host files do not specify the domain they serve explicitly using the ServerName directive, you will be asked to choose the virtual host file.

      When the installation is successfully finished, you will see a message similar to this:

      Output

      IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/example.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/example.com/privkey.pem Your cert will expire on 2020-09-24. To obtain a new or tweaked version of this certificate in the future, simply run certbot again with the "certonly" option. To non-interactively renew *all* of your certificates, run "certbot renew" - Your account credentials have been saved in your Certbot configuration directory at /etc/letsencrypt. You should make a secure backup of this folder now. This configuration directory will also contain certificates and private keys obtained by Certbot so making regular backups of this folder is ideal. - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le

      The generated certificate files will be available within a subdirectory named after your base domain in the /etc/letsencrypt/live directory.

      Now that your certificates are downloaded, installed, and loaded, you can check your SSL certificate status to make sure that everything is working.

      Step 3 — Testing the Certificate and SSL Configuration

      At this point, you can ensure that Certbot created your SSL certificate correctly by using the SSL Server Test from the cloud security company Qualys.

      Open the following link in your preferred web browser, replacing example.com with your domain:

      https://www.ssllabs.com/ssltest/analyze.html?d=example.com
      

      You will land on a page that immediately begins testing the SSL connection to your server:

      SSL Server Test

      Once the test starts running, it may take a few minutes to complete. The status of the test will update in your browser.

      When the testing finishes, the page will display a letter grade that rates the security and quality of your server’s configuration. At the time of this writing, default settings will give an A rating:

      SSL Report - A

      For more information about how SSL Labs determines these grades, check out the SSL Labs Grading post detailing the updates made to the grading scheme in January, 2018.

      Try reloading your website using https:// and notice your browser’s security indicator. It will now indicate that the site is properly secured, usually with a lock icon.

      With your SSL certificate installed and verified, the next step is to set up auto-renewal for your certificate to keep your certificate valid.

      Step 4 — Setting Up Auto Renewal

      Let’s Encrypt certificates are valid for 90 days, but it’s recommended that you check for renewal twice a day in case of a revocation or other problem. Because of this, it is a best practice to automate this process.

      First, let’s examine the command that you will use to renew the certificate. The certbot Let’s Encrypt client has a renew command that automatically checks the currently installed certificates and tries to renew them if they are less than 30 days away from the expiration date. By using the --dry-run option, you can run a simulation of this task to test how renew works:

      • sudo certbot renew --dry-run

      The output should look similar to this:

      Output

      Saving debug log to /var/log/letsencrypt/letsencrypt.log - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Processing /etc/letsencrypt/renewal/example.com.conf - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Cert not due for renewal, but simulating renewal for dry run Plugins selected: Authenticator apache, Installer apache Starting new HTTPS connection (1): acme-staging-v02.api.letsencrypt.org Renewing an existing certificate Performing the following challenges: http-01 challenge for example.com http-01 challenge for www.example.com Waiting for verification... Cleaning up challenges Resetting dropped connection: acme-staging-v02.api.letsencrypt.org - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - new certificate deployed with reload of apache server; fullchain is /etc/letsencrypt/live/example.com/fullchain.pem - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ** DRY RUN: simulating 'certbot renew' close to cert expiry ** (The test certificates below have not been saved.) Congratulations, all renewals succeeded. The following certs have been renewed: /etc/letsencrypt/live/example.com/fullchain.pem (success) ...

      Notice that if you created a bundled certificate with multiple domains, only the base domain name will be shown in the output, but the renewal will be valid for all domains included in this certificate.

      A practical way to ensure your certificates will not get outdated is to create a cron job that will periodically execute the automatic renewal command for you.

      The official Certbot documentation recommends running cron twice per day. This will ensure that, in case Let’s Encrypt initiates a certificate revocation, there will be no more than half a day before Certbot renews your certificate. The documentation suggests using the following command to add an appropriate cron job to the /etc/crontab crontab file:

      • echo "0 0,12 * * * root python3 -c 'import random; import time; time.sleep(random.random() * 3600)' && certbot renew -q" | sudo tee -a /etc/crontab > /dev/null

      This will create a new cron job that will execute at noon and midnight every day (0 0,12 * * *). It will then run the short python3 script, which pauses for a random period of time between zero and sixty minutes. This is recommended in order to reduce the load on Let’s Encrypt’s servers.

      After the python script exits, the actual certbot renew command will run.

      For more information on how to create and schedule cron jobs, you can check our How To Use Cron To Automate Tasks on CentOS 8 guide. More detailed information about renewal can be found in the Certbot documentation.

      Conclusion

      In this guide you installed the Let’s Encrypt Certbot client, downloaded SSL certificates for your domain, and set up automatic certificate renewal. If you have any questions about using Certbot, you can check the official Certbot documentation. We also recommend that you check the official Let’s Encrypt blog for important updates from time to time.



      Source link

      Cómo instalar el servidor dweb Apache en CentOS 8 [Guía de inicio rápido]


      Introducción

      El servidor HTTP Apache es el más usado del mundo. Ofrece muchas características potentes, entre las que se incluyen módulos que se cargan de forma dinámica, una sólida compatibilidad con medios y amplia integración con otras herramientas de software populares.

      A través de esta guía, instalará un servidor web Apache con hosts virtuales en su servidor de CentOS 8. Para acceder a una versión más detallada de este tutorial, consulte Cómo instalar el servidor web Apache en CentOS 8.

      Requisitos previos

      Necesitará lo siguiente para completar esta guía:

      Paso 1: Instalar Apache

      Apache está disponible dentro de los repositorios de software predeterminados de CentOS, lo cual significa que puede instalarlo con el administrador de paquetes dnf.

      Ya que configuramos un non-root sudo user en los requisitos previos, instale el paquete Apache:

      Una vez confirmada la instalación, dnf instalará Apache y todas las dependencias necesarias.

      Paso 2: Ajustar el firewall

      Al completar el paso 4 de la guía de Configuración inicial del servidor con CentOS 8 que se mencionó en la sección de requisitos previos, ya habrá instalado firewalld en su servidor para suministrar las solicitudes a través de HTTP.

      Si además piensa configurar Apache para que proporcione contenido a través de HTTPS, también le convendrá abrir el puerto 443 al habilitar el servicio https:

      • sudo firewall-cmd --permanent --add-service=https

      A continuación, vuelva a cargar el firewall para que entren en efecto estas nuevas reglas:

      • sudo firewall-cmd --reload

      Una vez que se vuelva a cargar el firewall, estará listo para iniciar el servicio y comprobar el servidor web.

      Paso 3: Comprobar su servidor web

      Una vez que la instalación se completa, Apache no se inicia automáticamente en CentOS, por lo que deberá iniciar el proceso de Apache de forma manual:

      • sudo systemctl start httpd

      Verifique que el servicio funcione con el siguiente comando:

      • sudo systemctl status httpd

      Obtendrá un estado active cuando el servicio esté en ejecución:

      Output

      ● httpd.service - The Apache HTTP Server Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disa> Active: active (running) since Thu 2020-04-23 22:25:33 UTC; 11s ago Docs: man:httpd.service(8) Main PID: 14219 (httpd) Status: "Running, listening on: port 80" Tasks: 213 (limit: 5059) Memory: 24.9M CGroup: /system.slice/httpd.service ├─14219 /usr/sbin/httpd -DFOREGROUND ├─14220 /usr/sbin/httpd -DFOREGROUND ├─14221 /usr/sbin/httpd -DFOREGROUND ├─14222 /usr/sbin/httpd -DFOREGROUND └─14223 /usr/sbin/httpd -DFOREGROUND ...

      Acceda a la página de inicio predeterminada de Apache para confirmar que el software se esté ejecutando correctamente mediante su dirección IP:

      http://your_server_ip
      

      Visualizará la página web predeterminada de Apache en CentOS 8:

      Página predeterminada de Apache para CentOS 8

      Esta página indica que Apache funciona correctamente. También incluye información básica sobre archivos y ubicaciones de directorios importantes de Apache.

      Paso 4: Configuración de hosts virtuales (recomendado)

      Cuando utilice el servidor web Apache, puede recurrir a los hosts virtuales (si está más familiarizado con Nginx, son similares a los bloques de servidor) para encapsular los detalles de configuración y alojar más de un dominio desde un único servidor. En este paso, configurará un dominio llamado example.com, pero debería cambiarlo por su propio nombre de dominio. Si va a configurar un nombre de dominio con DigitalOcean, consulte nuestra Documentación de red.

      Cree el directorio html para example.com como se muestra, usando el indicador -p para crear cualquier directorio principal necesario:

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

      Cree un directorio adicional para almacenar archivos de registro para el sitio:

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

      A continuación, asigne la propiedad del directorio html con la variable de entorno $USER:

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

      Asegúrese de que estén configurados los permisos predeterminados de su root web:

      • sudo chmod -R 755 /var/www

      A continuación, cree una página de ejemplo index.html utilizando vi o su editor favorito:

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

      Pulse i para realizar un cambio al modo INSERT y agregar el siguiente ejemplo HTML al archivo:

      /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>
      

      Guarde y cierre el archivo presionando ESC, escribiendo :wq y presionando ENTER.

      Una vez establecidos el directorio de su sitio y el archivo de índice de ejemplo, casi estará listo para crear archivos de host virtuales. Mediante los archivos de host virtuales se especifica la configuración de sus sitios individuales y se informa al servidor web de Apache la manera de responder a varias solicitudes de dominio.

      Antes de crear sus hosts virtuales, deberá crear un directorio sites-available para almacenarlos. También creará el directorio sites-enabled que indica a Apache que un host virtual está preparado para visitantes. En el directorio sites-enabled se almacenarán enlaces simbólicos a hosts virtuales que deseemos publicar. Cree ambos directorios con el siguiente comando:

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

      A continuación, indicará a Apache que busque hosts virtuales en el directorio sites-enabled. Para hacerlo, edite el archivo de configuración principal de Apache con vi o su editor preferido y agregue una línea que declare un directorio opcional para los archivos de configuración adicionales:

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

      Presione la G mayúscula para ir al final del archivo. A continuación, presione i para pasar al modo INSERT y agregue la siguiente línea al final del archivo:

      /etc/httpd/conf/httpd.conf

      ...
      # Supplemental configuration
      #
      # Load config files in the "/etc/httpd/conf.d" directory, if any.
      IncludeOptional conf.d/*.conf
      IncludeOptional sites-enabled/*.conf
      

      Guarde y cierre el archivo cuando termine de añadir esa línea. Ahora que están listos sus directorios de hosts virtuales, creará su archivo de host virtual.

      Comience creando un nuevo archivo en el directorio sites-available:

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

      Agregue el siguiente bloque de configuración y cambie el dominio example.com por su nombre de dominio:

      /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>
      

      Esto indicará a Apache dónde encontrar directamente el root que contiene los documentos web de acceso público. También, dónde almacenar errores y solicitar registros para este sitio en particular.

      Guarde y cierre el archivo cuando haya terminado.

      Ahora que creó archivos de host virtuales, los habilitará para que Apache sepa presentarlos a los visitantes. Para lograrlo, cree un enlace simbólico para cada host virtual en el directorio sites-enabled:

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

      Su host virtual quedará, así, configurado y listo para ofrecer contenido. Antes de reiniciar el servicio de Apache, nos aseguraremos de que a través de SELinux se implementen las políticas correctas para sus hosts virtuales.

      Paso 5: Ajustar los permisos de SELinux para hosts virtuales (recomendado)

      SELinux es un módulo de seguridad de kernel de Linux que aporta seguridad extrema a los sistemas Linux. CentOS 8 viene equipado con SELinux que está configurado para funcionar con la configuración predeterminada de Apache. Debido a que modificó la configuración predeterminada al configurar un directorio de registro personalizado en el archivo de configuración de los hosts virtuales, recibirá un error si intenta iniciar el servicio de Apache. Para resolver esto, deberá actualizar las políticas SELinux a fin de permitir que Apache escriba en los archivos necesarios.

      Existen diferentes formas de configurar políticas en función de las necesidades de su entorno, ya que SELinux le permite personalizar el nivel de seguridad. En este paso se abarcarán dos métodos de ajuste de políticas de Apache: el universal y el que se aplica a un directorio específico. Ajustar políticas en directorios es más seguro y, por lo tanto, es el enfoque recomendado.

      Ajustar políticas de Apache de forma universal

      Establecer la política de Apache de forma universal indicará a SELinux que trate de forma idéntica todos los procesos de Apache usando el booleano httpd_unified. Si bien este enfoque es más conveniente, no le brindará el mismo nivel de control que uno centrado en una política de archivos o directorios.

      Ejecute el siguiente comando para configurar una política universal de Apache:

      • sudo setsebool -P httpd_unified 1

      El comando setsebool cambia los valores booleanos de SELinux. El marcador -P actualizará el valor de tiempo de inicio y hará que este cambio persista en los reinicios. httpd_unified es el booleano que indicará a SELinux que trate todos los procesos de Apache como el mismo tipo, por lo que lo habrá habilitado con un valor de 1.

      Ajustar políticas de Apache en un directorio

      Configurar individualmente los permisos de SELinux para el directorio /var/www/example.com/log le brindará mayor control sobre sus políticas de Apache, pero también puede requerir más mantenimiento. Debido a que esta opción no establece políticas de forma universal, deberá fijar de forma manual el tipo de contexto para cualquier nuevo directorio de registro especificado en sus configuraciones de host virtuales.

      Primero, compruebe el tipo de contexto que SELinux dio al directorio /var/www/example.com/log:

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

      Este comando enumera e imprime el contexto de SELinux del directorio. Obtendrá un resultado similar al siguiente:

      Output

      drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_sys_content_t:s0 6 Apr 23 23:51 /var/www/example.com/log/

      El contexto actual es httpd_sys_content_t, que indica a SELinux que el proceso de Apache solo puede leer archivos creados en este directorio. A través de este tutorial, cambiará el tipo de contexto del directorio /var/www/example.com/log a httpd_log_t. Este tipo permitirá que Apache genere archivos de registro de la aplicación web y realice anexos a ellos:

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

      A continuación, utilice el comando restorecon para aplicar estos cambios y hacer que persistan a través de los reinicios:

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

      El indicador -R ejecuta este comando de forma recursiva, lo que significa que actualizará cualquier archivo existente para que utilice el nuevo contexto. El indicador -v imprimirá los cambios de contexto realizados por el comando. Obtendrá el siguiente resultado que confirma los cambios:

      Output

      Relabeled /var/www/example.com/log from unconfined_u:object_r:httpd_sys_content_t:s0 to unconfined_u:object_r:httpd_log_t:s0

      Puede enumerar los contextos una vez más para ver los cambios:

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

      El resultado refleja el tipo de contexto actualizado:

      Output

      drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_log_t:s0 6 Apr 23 23:51 /var/www/example.com/log/

      Ahora que el directorio /var/www/example.com/log usa el tipo httpd_log_t, estará listo para probar su configuración de host virtual.

      Paso 6: Probar el host virtual (recomendado)

      Una vez que el contexto se SELinux se haya actualizado con cualquiera de los métodos, Apache podrá realizar tareas de escritura en el directorio /var/www/example.com/log. Ahora podrá reiniciar con éxito el servicio de Apache:

      • sudo systemctl restart httpd

      Enumere el contenido del directorio /var/www/example.com/log para ver si Apache creó los archivos de registro:

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

      Se le confirmará que Apache pudo crear los archivos error.log y requests.log especificados en la configuración del host virtual:

      Output

      -rw-r--r--. 1 root root system_u:object_r:httpd_log_t:s0 0 Apr 24 00:06 error.log -rw-r--r--. 1 root root system_u:object_r:httpd_log_t:s0 0 Apr 24 00:06 requests.log

      Ahora que tiene su host virtual configurado y los permisos SELinux actualizados, Apache proporcionará su nombre de dominio. Puede comprobarlo visitando http://example.com, donde debería ver algo como esto:

      ¡Éxito! ¡El host virtual example.com funciona!

      Esto confirma que su host virtual está correctamente configurado y ofrece contenido. Repita los pasos 4 y 5 para crear nuevos hosts virtuales con permisos de SELinux para dominios adicionales.

      Conclusión

      A través de este tutorial, instaló y gestionó el servidor web de Apache. Ahora que ha instaló su servidor web, dispone de varias opciones respecto del tipo de contenido que puede ofrecer y de las tecnologías que puede utilizar para crear una experiencia más completa.

      Si quiere construir una pila de aplicaciones más completa, puede consultar este artículo sobre cómo configurar una pila LAMP en CentOS 8.



      Source link