One place for hosting & domains

      Apache

      How To Configure MTA-STS and TLS Reporting for Your Domain Using Apache on Ubuntu 18.04


      The author selected Electronic Frontier Foundation Inc to receive a donation as part of the Write for DOnations program.

      Introduction

      Mail Transport Agent Strict Transport Security (MTA-STS) is a new internet standard that allows you to enable strict force-TLS for email sent between supported email providers. It is similar to HTTP Strict Transport Security (HSTS), where a force-TLS policy is set and then cached for a specified amount of time, reducing the risk of man-in-the-middle or downgrade attacks.

      MTA-STS is complemented by SMTP TLS Reporting (TLSRPT), which gives you insight into which emails are successfully delivered over TLS, and which aren’t. TLSRPT is similar to DMARC reporting, but for TLS.

      The primary reason for implementing MTA-STS for your domain is to ensure that confidential email that is sent to you is transmitted securely over TLS. Other methods for requiring TLS for email communications are still susceptible to man-in-the-middle attacks, as the initial connection is unencrypted. MTA-STS ensures that the initial incoming connection is using TLS by default, which greatly reduces the risk of these attacks.

      An example use case for MTA-STS and TLS Reporting is to help create a secure customer service email system for your business. Customers may send support tickets via email that contain confidential personal information, which needs a secure TLS connection. MTA-STS provides that secure connection, and TLSRPT will deliver daily reports identifying any emails that weren’t sent securely—giving crucial insight into any ongoing or previous attacks against your email system.

      In this tutorial, you will learn how to configure MTA-STS and TLSRPT for your domain name, and then interpret your first TLS Report. While this tutorial covers the steps for using Apache on Ubuntu 18.04 with a Let’s Encrypt certificate, the MTA-STS/TLSRPT configuration will also work on alternatives, such as Nginx on Debian.

      Prerequisites

      Before you begin this guide, you’ll need:

      Once you have these ready, log in to your server as your non-root user to begin.

      Note: Once you have completed the implementation steps for MTA-STS and TLSRPT, you may have to wait up to 24 hours to receive your first TLS Report. This is because most email providers send reports once per day. You may resume the tutorial from Step 5 once you’ve received your first report.

      Step 1 — Creating an MTA-STS Policy File

      MTA-STS is enabled and configured using a plain text configuration file that you host on your website. Supported mail servers will then automatically connect to your website to retrieve the file, which causes MTA-STS to be enabled. In this first step you’ll understand the available options for this file and choose the most appropriate for your file.

      Firstly, open a new text file in your home directory so that you have somewhere to write down your desired configuration:

      We will first go over an example, and then you will write your own configuration file.

      Following is an example of an MTA-STS configuration file:

      Example MTA-STS Configuration File

      version: STSv1
      mode: enforce
      mx: mail1.your-domain
      mx: mail2.your-domain
      max_age: 604800
      

      This example configuration file specifies that all email delivered to mail1.your-domain and mail2.your-domain from supported providers must be delivered over a valid TLS connection. If a valid TLS connection cannot be established with your mail server (for example, if the certificate has expired or is self-signed), the email will not be delivered.

      This will make it much more challenging for an attacker to intercept and snoop on/modify your email in a situation like a man-in-the-middle attack. This is because having MTA-STS enabled properly only allows email to be transmitted over a valid TLS connection, which requires a valid TLS certificate. It would be hard for an attacker to acquire such a certificate, as doing so usually requires privileged access to your domain name and/or website.

      As shown in the example earlier in this step, the configuration file consists of a number of key/value pairs:

      • version:

        • Purpose: To specify the version of the MTA-STS specification to use.
        • Accepted Values: Currently the only accepted value is STSv1.
        • Example: version: STSv1
      • mode:

        • Purpose: Specify which mode MTA-STS should be enabled in.
        • Accepted Values:
          • enforce: Force all incoming email from supported providers to use valid TLS.
          • testing: Report-only mode. email will not be blocked, but TLSRPT reports are still sent.
          • none: Disable MTA-STS.
        • Example: mode: enforce
      • mx:

        • Purpose: To specify which mail servers are allowed to handle email for your domain. This should match the servers specified in your mx records.
        • Accepted Values: Fully-qualified domain name of a mail server, or a wildcard host. Multiple mx: values must be used to specify multiple mail servers.
        • Example: mx: mail1.your-domain, mx: mail2.your-domain, mx: *.example.org
      • max_age:

        • Purpose: To specify the maximum lifetime of the MTA-STS policy, in seconds.
        • Accepted Values: Any positive integer up to 31557600.
        • Example: max_age: 604800 (1 week)

      You can also view the official specification for the key/value pairs in Section 3.2 of the MTA-STS RFC.

      Warning: Enabling MTA-STS in enforce mode could unexpectedly cause some email not to be delivered to you. Instead, it is recommended to use mode: testing and a low max_age: value at first, in order to ensure that everything is working correctly before turning on MTA-STS fully.

      Using the example file earlier in the step, as well as the preceding key/value pair examples, write your desired MTA-STS policy file and save it to the file that you created at the start of the step.

      The following example file is ideal for testing MTA-STS, as it will not cause any emails to be unexpectedly blocked, and has a max_age of only 1 day, meaning that if you decide to disable it, the configuration will expire quickly. Note that some email providers will only send TLSRPT reports if the max_age is greater than 1 day, which is why 86401 seconds is a good choice (1 day and 1 second).

      Example Test MTA-STS Configuration File

      version: STSv1
      mode: testing
      mx: mail1.your-domain
      mx: mail2.your-domain
      max_age: 86401
      

      In this step you created your desired MTA-STS configuration file and saved it to your home area. In the next step, you will configure an Apache web server to serve the file in the correct format.

      Step 2 — Configuring Apache to Serve Your MTA-STS Policy File

      In this step, you’ll configure an Apache virtual host to serve your MTA-STS configuration file, and then add a DNS record to allow the site to be accessed from a subdomain.

      In order for your MTA-STS configuration file to be automatically discovered by mail servers, it must be served at exactly the right path: https://mta-sts.your-domain/.well-known/mta-sts.txt. You must use the mta-sts subdomain over HTTPS and the /.well-known/mta-sts.txt path, otherwise your configuration will not work.

      This can be achieved by creating a new Apache virtual host for the mta-sts subdomain, which will serve the MTA-STS policy file. This step builds upon the base configuration that you’ll have set up in the prerequisite step How to Install the Apache Web Server on Ubuntu 18.04.

      Firstly, create a directory for your virtual host:

      • sudo mkdir /var/www/mta-sts

      If you’re hosting multiple different domains on your web server, it is recommended to use a different MTA-STS virtual host for each, for example /var/www/mta-sts-site1 and /var/www/mta-sts-site2.

      Next, you need to create the .well-known directory, which is where your MTA-STS configuration file will be stored. .well-known is a standardized directory for ‘well-known’ files, such as TLS certificate validation files, security.txt, and more.

      • sudo mkdir /var/www/mta-sts/.well-known

      Now you can move the MTA-STS policy file that you created in Step 1 into the web server directory that you just created:

      • sudo mv ~/mta-sts.txt /var/www/mta-sts/.well-known/mta-sts.txt

      You can check that the file was copied correctly if you wish:

      • cat /var/www/mta-sts/.well-known/mta-sts.txt

      This will output the contents of the file that you created in Step 1.

      In order for Apache to serve the file, you’ll need to configure the new virtual host and enable it. MTA-STS only works over HTTPS, so you’ll use port 443 (HTTPS) exclusively, rather than using port 80 (HTTP) as well.

      Firstly, create a new virtual host configuration file:

      • sudo nano /etc/apache2/sites-available/mta-sts.conf

      Like with the virtual host directory, if you are hosting multiple different domains on the same web server, it is recommended to use a different virtual host name for each.

      Then, copy the following sample configuration into the file, and populate the variables where required:

      ~/etc/apache2/sites-available/mta-sts.conf

      <IfModule mod_ssl.c>
      <VirtualHost your-server-ipv4-address:443 [your-server-ipv6-address]:443>
          ServerName mta-sts.your-domain
          DocumentRoot /var/www/mta-sts
      
          ErrorDocument 403 "403 Forbidden - This site is used to specify the MTA-STS policy for this domain, please see '/.well-known/mta-sts.txt'. If you were not expecting to see this, please use <a href="https://your-domain" rel="noopener">https://your-domain</a> instead."
      
          RewriteEngine On
          RewriteOptions IgnoreInherit
          RewriteRule !^/.well-known/mta-sts.txt - [L,R=403]
      
          SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
          SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
          Include /etc/letsencrypt/options-ssl-apache.conf
      </VirtualHost>
      </IfModule>
      

      This configuration will create the mta-sts virtual host, which will be served at mta-sts.your-domain. It will also redirect all requests, except for those to the mta-sts.txt file itself, to a custom 403 Forbidden error page, with a friendly explanation of what the subdomain site is for. This is to help ensure that any visitors who accidentally come across your MTA-STS site aren’t inadvertently confused.

      Currently, a self-signed TLS certificate is used. This is not ideal, as a fully valid/trusted certificate is required for MTA-STS to work correctly. In Step 3, you will acquire a TLS certificate using Let’s Encrypt.

      Next, ensure that the required Apache modules are enabled:

      After that, enable the new virtual host:

      Then, run a syntax check of the Apache configuration files, to ensure that there aren’t any unexpected errors:

      • sudo apachectl configtest

      When the test passes with no errors, you can restart Apache to fully enable the new virtual host:

      • sudo service apache2 restart

      Now that the Apache virtual host has been set up and configured, you need to create the required DNS record(s) to allow it to be accessed using the fully-qualified domain name mta-sts.your-domain.

      The way that this is done depends on the DNS hosting provider that you use. However, if you use DigitalOcean as your DNS provider, simply navigate to your project, followed by clicking on your domain.

      Finally, add the required DNS records for the mta-sts subdomain. If your Droplet only uses IPv4, create an A record for mta-sts, pointing to your-server-ipv4-address. If you use IPv6 as well, create an AAAA record pointing to your-server-ipv6-address.

      A screenshot of the DigitalOcean DNS control panel, showing an example DNS record for mta-sts pointing to an IPv4 address.

      In this step, you created and configured a new Apache virtual host for your MTA-STS subdomain, then added the required DNS record(s) to allow it to be accessed easily. In the next step, you will acquire a trusted Let’s Encrypt certificate for your MTA-STS subdomain.

      Step 3 — Acquiring a Let’s Encrypt Certificate for Your MTA-STS Subdomain

      In this step, you’ll acquire a TLS certificate from Let’s Encrypt, to allow your mta-sts.your-domain site to be served correctly over HTTPS.

      In order to do this, you’ll use certbot, which you set up as part of the prerequisite step How To Secure Apache with Let’s Encrypt on Ubuntu 18.04.

      Firstly, run certbot to issue a certificate for your mta-sts subdomain using the Apache plugin verification method:

      • sudo certbot --apache -d mta-sts.your-domain

      This will automatically issue a trusted certificate and install it on your Apache web server. When the Certbot wizard asks about configuring a HTTP -> HTTPS redirect, select 'No’, as this is not required for MTA-STS.

      To finish, test your new virtual host to ensure that it is working correctly. Use a web browser to visit https://mta-sts.your-domain/.well-known/mta-sts.txt, or use a command-line tool such as curl:

      • curl https://mta-sts.your-domain/.well-known/mta-sts.txt

      This will output the MTA-STS policy file that you created in Step 1:

      Output

      version: STSv1 mode: testing mx: mail1.your-domain mx: mail2.your-domain max_age: 86401

      If an error occurs, ensure that the virtual host configuration from Step 2 is correct, and that you have added a DNS record for the mta-sts subdomain.

      In this step, you issued a Let’s Encrypt TLS certificate for your mta-sts subdomain, and tested that it’s working. Next, you’ll set some DNS TXT records to fully enable MTA-STS and TLSRPT.

      Step 4 — Configuring the DNS Records Required to Enable MTA-STS and TLSRPT

      In this step, you’ll configure two DNS TXT records, which will fully enable the MTA-STS policy that you have already created, and also enable TLS Reporting (TLSRPT).

      These DNS records can be configured using any DNS hosting provider, but in this example, DigitalOcean is used as the provider.

      Firstly, log on to your DigitalOcean control panel and navigate to your project, followed by clicking on your domain.

      You then need to add the following two TXT records:

      _mta-sts.your-domain IN TXT "v=STSv1; id=id-value"
      _smtp._tls.your-domain IN TXT "v=TLSRPTv1; rua=reporting-address"
      

      id-value is a string used to identify the version of your MTA-STS policy in place. If you update your policy, you’ll need to also update the id value to ensure that the new version is detected by mail providers. It is recommended to use the current date stamp as the id, for example 20190811231231 (23:12:31 on 11th Aug 2019).

      reporting-address is the address where your TLS reports will be sent to. This can be either an email address prefixed with mailto:, or a web URI, for example for an API that collects reports. The reporting address doesn’t have to be an address on your-domain. You may use a completely different domain if you wish.

      For example, the following two sample records are both valid:

      _mta-sts.your-domain IN TXT "v=STSv1; id=20190811231231"
      _smtp._tls.your-domain IN TXT "v=TLSRPTv1; rua=mailto:tls-reports@your-domain"
      

      Adjust the variables as required, and set these DNS TXT records in your DigitalOcean control panel (or whichever DNS provider you’re using):

      A screenshot of the DigitalOcean control panel, showing the _mta-sts DNS TXT record being set.

      A screenshot of the DigitalOcean control panel, showing the _smtp._tls DNS TXT record being set.

      Once these DNS records have been set and have propagated, MTA-STS will be enabled with the policy that you created in Step 1, and will begin to receive TLSRPT reports at the address that you specified.

      In this step, you configured the DNS records required for MTA-STS to be enabled. Next, you will receive and then interpret your first TLSRPT report.

      Step 5 — Interpreting Your First TLSRPT Report

      Now that you’ve enabled MTA-STS and TLSRPT (TLS Reporting) for your domain, you will begin to receive reports from supported email providers. These reports will show the number of emails that were or were not successfully delivered over TLS, and the reasons for any errors.

      Different email providers send their reports at different times; for example, Google Mail sends their reports daily at around 10:00 UTC.

      Depending on how you configured the TLSRPT DNS record in Step 5, you will either receive your reports via email, or via a web API. This tutorial focuses on the email method, as that is the most common configuration.

      If you’ve just completed the rest of this tutorial, wait until you receive your first report, then you can resume.

      Your daily TLSRPT report via email will usually have a subject line similar to the following:

      Report Domain: your-domain Submitter: google.com Report-ID: <2019.08.10T00.00.00Z+your-domain@google.com>
      

      This email will have an attachment in .gz format, which is a Gzip compressed archive, with a file name similar to the following:

      google.com!your-domain!1565222400!1565308799!001.json.gz
      

      For the rest of this tutorial this file will be referred to as report.json.gz.

      Save this file to your local machine, and extract it using whichever tool you prefer.

      If you’re using a Debian-based Linux system, you will be able to run the gzip -d command to decompress the archive:

      This will result in a JSON file called report.json.

      Next, you can view the report either directly as the raw JSON string, or use your favorite JSON prettifier to put it into a more readable format. In this example, jq will be used, but you could also use Python’s json.tool if you wish.

      Note: If you don’t have jq installed, you can install it using apt install jq. Or, for other operating systems use the necessary installation instructions from jq.

      This will output something similar to the following:

      Prettified report.json

      { "organization-name": "Google Inc.", "date-range": { "start-datetime": "2019-08-10T00:00:00Z", "end-datetime": "2019-08-10T23:59:59Z" }, "contact-info": "smtp-tls-reporting@google.com", "report-id": "2019-08-10T00:00:00Z_your-domain", "policies": [ { "policy": { "policy-type": "sts", "policy-string": [ "version: STSv1", "mode: testing", "mx: mail1.your-domain", "mx: mail2.your-domain", "max_age: 86401" ], "policy-domain": "your-domain" }, "summary": { "total-successful-session-count": 230, "total-failure-session-count": 0 } } ] }

      The report shows the provider that generated the report and the reporting period, as well as the MTA-STS policy that was applied. However, the main section that you’ll be interested in is summary, specifically the successful and failed session counts.

      This sample report shows that 230 emails were successfully delivered over TLS from the mail provider that generated the report, and 0 email deliveries failed to establish a proper TLS connection.

      In the event that there is a failure—for example, if a TLS certificate expires or there is an attacker on the network—the failure mode will be documented in the report. Some examples of failure modes are:

      • starttls-not-supported: If the receiving mail server doesn’t support STARTTLS.
      • certificate-expired: If a certificate has expired.
      • certificate-not-trusted: If a self-signed or other non-trusted certificate is used.

      In this final step, you received and then interpreted your first TLSRPT report.

      Conclusion

      In this article you set up and configured MTA-STS and TLS Reporting for your domain, and interpreted your first TLSRPT report.

      Once MTA-STS has been enabled and working stably for a while, it is recommended to adjust the policy, increasing the max_age value, and eventually switching it to enforce mode once you are sure that all email from supported providers is being delivered successfully over TLS.

      Finally, if you’d like to learn more about the MTA-STS and TLSRPT specifications, you can review the RFCs for both of them:



      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

      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