One place for hosting & domains

      SSL

      How to Fix Common SSL Issues in WordPress (5 Key Solutions)


      A few years ago, Google announced that it would begin flagging websites that don’t have a Secure Sockets Layer (SSL) certificate installed. While setting up an SSL certificate tends to be pretty straightforward, you may encounter some errors in the process.

      The good news is that many of these errors have simple fixes. Therefore, if you run into a problem when trying to move a current WordPress site to SSL, there’s no need to panic. All it takes is a little troubleshooting to get your site working properly (and securely) in no time.

      In this post, we’ll start by discussing the importance of SSL certificates on your website. Then we’ll provide you with a list of five common SSL issues and show you how to fix them on your WordPress site. Let’s get started!

      Do More with DreamPress

      DreamPress’ automatic updates and strong security defenses take server management off your hands so you can focus on content creation.

      An Overview of SSL (And Why It’s Important)

      SSL enables you to ensure that your website delivers a secure connection via Hypertext Transfer Protocol Secure (HTTPS) protocol. In a nutshell, this is the updated, secure version of HTTP. Since it’s encrypted, HTTPS increases the security of any data that is transferred.

      Installing an SSL certificate on your WordPress site is important for several reasons. For starters, it enables the web server and browser to communicate over a secure connection.

      Moreover, SSL/HTTPS can help prevent security breaches that can compromise not only your personal information but your customers’ as well. For this reason, Google now penalizes sites that don’t have an SSL certificate.

      For example, it may display a “not secure” or “your connection is not private” warning message to users who try to access the site.

      A “Your connection is not private” warning message in Google Chrome.

      The exact wording of the message may vary depending on the browser you’re using, but the concept is the same. Ultimately, this can hurt your engagement. Additionally, it can hamper your Search Engine Optimization rankings.

      Finally, not having SSL properly configured can also limit what type of site you’re able to run. For instance, if you want to start an online store, you’ll need SSL/HTTPS encryption to accept online payments via gateways such as Stripe, PayPal, and Authorize.net.

      How to Fix Common SSL Issues in WordPress (5 Key Solutions)

      Now that we understand a little more about what SSL/HTTPS is and why it’s important, let’s get into the issues that can come from it. Below are five of the most common SSL problems in WordPress and how to resolve them.

      1. The NET::ERR_CERT_INVALID Error

      If you’re a Google Chrome user, one of the most common issues you might run into is an error message that reads “NET::ERR_CERT_INVALID.”

      A CERT: ERR_AUTHORITY_INVALID error message in Chrome.

      This can happen in other browsers, too, though the message may differ slightly. In any case, it simply means that the connection to the site is not secure.

      If you have an SSL certificate installed on your site, this likely means something is wrong with the settings or configuration, and therefore the browser cannot read and accept it properly. When this is the case, there are a few steps you can take.

      First, you’ll want to make sure the certificate is assigned to the correct domain or subdomain. Next, you’ll need to check that your certificate is not expired. You can do this by clicking on the padlock icon to the left of the browser address bar.

      Details of the certificate will appear, and you’ll want to make sure it says “Valid.” If it says “not valid,” you’ll need to renew it as soon as possible through the issuing provider, also listed here.

      If you installed the certificate yourself, you could try reinstalling it. However, you may want to use a different provider this time, as your browser may not recognize the issuing authority of your current certificate. We recommend using Let’s Encrypt.

      The Let’s Encrypt website.

      Finally, if the certificate is assigned to the correct domain and is updated, you may want to contact your hosting provider. If they installed the certificate, they might know what steps to take to resolve the issue.

      2. Mixed Content Errors

      Another common type of error you may encounter when moving to SSL is mixed content warnings. In a nutshell, this is what happens when images, scripts, or stylesheets on your site load while using the old, unsecured HTTP protocol. In other words, some of your WordPress content is secure while other parts aren’t.

      There are two methods you can use to fix mixed content errors. The first is to use a plugin such as Really Simple SSL.

      The Really Simple SSL plugin.

      Once you install and activate the tool on your website, you can locate the plugin settings by navigating to Settings > SSL.

      The Really Simple SSL plugin settings in WordPress.

      However, you don’t need to take any further action to fix the mixed content errors. The plugin automatically does that upon activation.

      The second method you can use is to manually fix the warnings. To get started, you can navigate to Settings > General in WordPress.

      Under WordPress Address (URL) and Site Address (URL), check to make sure that the URLs are using “https.”

      The WordPress General settings screen.

      After you save your changes, you can install the Better Search Replace plugin.

      The WordPress Better Search Replace plugin.

      With this tool, you can easily search for, find, and replace old URLs within your WordPress database. Once you activate it, you can navigate to Tools > Better Search Replace.

      The Better Search Replace plugin settings.

      In the Search for field, you can add your website URL with “http” at the beginning. Then, add “https” to the Replace with field.

      When you’re done, save your changes. Now the mixed content errors should be gone when you refresh your site.

      3. Too Many Redirects

      Another SSL issue you may run into is the too many redirects error. This might happen because WordPress lets you enforce SSL/HTTPS for the admin area of your site.

      To resolve this error, you’ll need to edit your wp-config.php file. You can locate this file by using a Secure File Transfer Protocol (SFTP) client like FileZilla or the file manager in your web hosting account.

      If you have a DreamHost account, start by navigating to Websites > Files in the sidebar. Then, locate your domain and click on the Manage Files button.

      Accessing the file manager in your DreamHost account

      This will take you to the file manager. To access your site’s directory, you’ll need to open the folder labeled with your domain name. Inside it, you’ll find the wp-config.php file.

      If you’re using FileZilla, the first step is to connect to your WordPress site. If this is your first time using the FTP client, you’ll need to obtain your credentials from your web host. Once connected, locate the wp-config.php file in your site’s directory.

      Locating the wp-config.php file in FileZilla.

      Open the file and insert the following snippet of code:

      define('FORCE_SSL_ADMIN', true);
      
      // in some setups HTTP_X_FORWARDED_PROTO might contain
      
      // a comma-separated list e.g. http,https
      
      // so check for https existence
      
      if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
      
             $_SERVER['HTTPS']='on';

      Note that you should add this at the bottom of the file, right before the line that reads, “That’s all, stop editing! Happy blogging.” When you’re ready, save your changes and close the file.

      4. HTTP to HTTPS Redirect

      By default, WordPress won’t automatically redirect your site from HTTP to HTTPS. Instead, you’ll need to tell it to do so. In some cases, you can use a plugin such as Really Simple SSL.

      However, you can also manually configure the HTTP to HTTPS redirect by editing your .htaccess file. Again, you can do this via SFTP or the file manager in your hosting account.

      Locate and open the .htaccess file, then add in the following code:

      <IfModule mod_rewrite.c>
      
      RewriteEngine On
      
      RewriteCond %{HTTPS} off
      
      RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
      
      </IfModule>

      Remember to save your changes when you’re done. If you’re not comfortable editing your site’s files, we recommend using a plugin or contacting your hosting provider for assistance.

      5. A Name Mismatch Error

      A fifth common SSL issue you may run into is the name mismatch error, which we briefly touched on earlier. This occurs when your domain name listed in the SSL certificate does not match the browser URL. This normally happens when you purchase a certificate from a third-party seller.

      To fix this error, you’ll simply need to add the following code to your .htaccess file:

      <IfModule mod_rewrite.c>
      
      RewriteEngine On
      
      RewriteCond %{HTTPS} off
      
      RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
      
      </IfModule>

      Save your changes when you’re done. Then, when you revisit your WordPress site, you should no longer see any SSL error messages.

      Protect Your Website with DreamShield

      For just $3/month, our premium security add-on scans your site weekly to ensure it is free of malicious code.

      How to Fix Other Common WordPress Errors

      Do you want to learn how to resolve other technical issues on your site? We’ve put together several guides to help you troubleshoot some of the most common WordPress errors:

      Check out our WordPress Tutorials section if you’re looking for tips and best practices for running a WordPress site. This is a collection of expert-written guides designed to help you navigate the WordPress dashboard like a pro.

      Conclusion

      Adding an SSL certificate to your WordPress website is essential. This will help you ensure that your content is accessed via a secure HTTPS connection. However, setting one up can cause a variety of issues.

      In this post, we discussed five common SSL errors and showed you how to resolve them:

      1. The NET::ERR_CERT_INVALID error. This suggests that your certificate needs to be renewed or reinstalled.
      2. Mixed content errors. You can fix this manually or with a plugin such as Really Simple SSL.
      3. Too many redirects. You may be able to resolve this issue by adding code to your wp-config.php file.
      4. A WordPress HTTP to HTTPS redirect. You can configure this manually via your site’s .htaccess file or by using a plugin such as Really Simple SSL.
      5. A name mismatch error. This happens when the certificate domain and browser URL do not match, in which case you’ll need to add code to your .htaccess file.

      Do you need help choosing and installing an SSL certificate on your WordPress site? When you use DreamHost as your hosting provider, this is an effortless process. Check out our DreamPress plans to learn more!



      Source link

      How To Use Certbot Standalone Mode to Retrieve Let’s Encrypt SSL Certificates on Ubuntu 20.04


      Introduction

      Let’s Encrypt is a service offering free SSL certificates through an automated API. The most popular Let’s Encrypt client is EFF’s Certbot.

      Certbot offers a variety of ways to validate your domain, fetch certificates, and automatically configure Apache and Nginx. In this tutorial, we’ll discuss Certbot’s standalone mode and how to use it to secure other types of services, such as a mail server or a message broker like RabbitMQ.

      We won’t discuss the details of SSL configuration, but when you are done you will have a valid certificate that is automatically renewed. Additionally, you will be able to automate reloading your service to pick up the renewed certificate.

      Prerequisites

      Before starting this tutorial, you will need:

      • An Ubuntu 20.04 server with a non-root, sudo-enabled user and basic firewall set up, as detailed in this Ubuntu 20.04 server setup tutorial.
      • A domain name pointed at your server. If you are using a DigitalOcean Droplet, you can accomplish this by following our “Domains and DNS” documentation. This tutorial will use your_domain throughout.
      • Port 80 or 443 must be unused on your server. If the service you’re trying to secure is on a machine with a web server that occupies both of those ports, you’ll need to use a different mode such as Certbot’s webroot mode.

      Step 1 — Installing Certbot

      Certbot recommends using their snap package for installation. Snap packages work on nearly all Linux flavours, but they required that you’ve installed snapd first in order to manage snap packages. Ubuntu 20.04 comes with support for snaps out of the box, so you can start by making sure your snapd core is up to date:

      • sudo snap install core; sudo snap refresh core

      If you’re working on a server that previously had an older version of certbot installed, you should remove it before going any further:

      After that, you can install the certbot package:

      • sudo snap install --classic certbot

      Finally, you can link the certbot command from the snap install directory to your path, so you’ll be able to run it by just typing certbot. This isn’t necessary with all packages, but snaps tend to be less intrusive by default, so they don’t conflict with any other system packages by accident:

      • sudo ln -s /snap/bin/certbot /usr/bin/certbot

      Now that we have Certbot installed, let’s run it to get our certificate.

      Step 2 — Running Certbot

      Certbot needs to answer a cryptographic challenge issued by the Let’s Encrypt API in order to prove we control our domain. It uses ports 80 (HTTP) or 443 (HTTPS) to accomplish this. Open up the appropriate port(s) in your firewall:

      Output

      Rule added Rule added (v6)

      We can now run Certbot to get our certificate. We’ll use the --standalone option to tell Certbot to handle the challenge using its own built-in web server. Finally, the -d flag is used to specify the domain you’re requesting a certificate for. You can add multiple -d options to cover multiple domains in one certificate.

      • sudo certbot certonly --standalone -d your_domain

      When running the command, you will be prompted to enter an email address and agree to the terms of service. After doing so, you should see a message telling you the process was successful and where your certificates are stored:

      Output

      IMPORTANT NOTES: Successfully received certificate. Certificate is saved at: /etc/letsencrypt/live/your_domain/fullchain.pem Key is saved at: /etc/letsencrypt/live/your_domain/privkey.pem This certificate expires on 2022-02-10. These files will be updated when the certificate renews. Certbot has set up a scheduled task to automatically renew this certificate in the background. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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

      You should now have your certificates. In the next step, we will inspect some of the files that we downloaded and learn about their functionality.

      Step 3 — Configuring Your Application

      Configuring your application for SSL is beyond the scope of this article, as each application has different requirements and configuration options, but let’s take a look at what Certbot has downloaded for us. Use ls to list out the directory that holds our keys and certificates:

      • sudo ls /etc/letsencrypt/live/your_domain

      Output

      cert.pem chain.pem fullchain.pem privkey.pem README

      The README file in this directory has more information about each of these files. Most often you’ll only need two of these files:

      • privkey.pem: This is the private key for the certificate. This needs to be kept safe and secret, which is why most of the /etc/letsencrypt directory has very restrictive permissions and is accessible by only the root user. Most software configuration will refer to this as something similar to ssl-certificate-key or ssl-certificate-key-file.
      • fullchain.pem: This is our certificate, bundled with all intermediate certificates. Most software will use this file for the actual certificate, and will refer to it in their configuration with a name like ‘ssl-certificate’.

      For more information on the other files present, refer to the “[Where are my certificateshttps://eff-certbot.readthedocs.io/en/stable/using.html#where-are-my-certificates)” section of the Certbot docs.

      Some software will need its certificates in other formats, in other locations, or with other user permissions. It is best to leave everything in the letsencrypt directory, and not change any permissions in there (permissions will just be overwritten upon renewal anyway), but sometimes that’s just not an option. In that case, you’ll need to write a script to move files and change permissions as needed. This script will need to be run whenever Certbot renews the certificates, which we’ll talk about next.

      Step 4 — Handling Certbot Automatic Renewals

      Let’s Encrypt’s certificates are only valid for ninety days. This is to encourage users to automate their certificate renewal process. The certbot package we installed takes care of this for us by adding a renew script to /etc/cron.d. This script runs twice a day and will renew any certificate that’s within thirty days of expiration.

      With our certificates renewing automatically, we still need a way to run other tasks after a renewal. We need to at least restart or reload our server to pick up the new certificates, and as mentioned in Step 3 we may need to manipulate the certificate files in some way to make them work with the software we’re using. This is the purpose of Certbot’s renew_hook option.

      To add a renew_hook, we update Certbot’s renewal config file. Certbot remembers all the details of how you first fetched the certificate, and will run with the same options upon renewal. We just need to add in our hook. Open the config file with you favorite editor:

      • sudo nano /etc/letsencrypt/renewal/your_domain.conf

      A text file will open with some configuration options. You can add a hook on the last line that will reload any web-facing services, making them use the renewed certificate:

      your_domain.conf’>/etc/letsencrypt/renewal/your_domain.conf

      renew_hook = systemctl reload your_service
      

      Update the command above to whatever you need to run to reload your server or run your custom file munging script. Usually, on Ubuntu, you’ll mostly be using systemctl to reload a service. Save and close the file, then run a Certbot dry run to make sure the syntax is ok:

      • sudo certbot renew --dry-run

      If you see no errors, you’re all set. Certbot is set to renew when necessary and run any commands needed to get your service using the new files.

      Conclusion

      In this tutorial, we’ve installed the Certbot Let’s Encrypt client, downloaded an SSL certificate using standalone mode, and enabled automatic renewals with renew hooks. This should give you a good start on using Let’s Encrypt certificates with services other than your typical web server.

      For more information, please refer to Certbot’s documentation.



      Source link

      How To Create a Self-Signed SSL Certificate for Nginx in Ubuntu 20.04


      Introduction

      TLS, or transport layer security, and its predecessor SSL, which stands for secure sockets layer, are web protocols used to protect and encrypt traffic over a computer network.

      With TLS/SSL, servers can send traffic safely between the server and clients without the possibility of the 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 Nginx web server on an Ubuntu 20.04 server.

      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 the 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.

      Prerequisites

      Before you begin, you should have a non-root user configured with sudo privileges and a firewall enabled. You can learn how to set up such a user account by following our initial server setup for Ubuntu 20.04.

      You will also need to have the Nginx web server installed. Follow our guide on installing Nginx on Ubuntu 20.04. Make sure to complete Step 5 of this tutorial and set up a server block, as this will be necessary to test whether Nginx is able to encrypt connections using your self-signed certificate.

      If you would like to install an entire LEMP (Linux, Nginx, MySQL, PHP) stack on your server, you can follow our guide on setting up LEMP on Ubuntu 20.04 instead of the standalone Nginx installation guide.

      Step 1 – Creating the SSL Certificate

      TLS/SSL functions by a combination of a public certificate and a private key. The SSL key is kept secret on the server and encrypts 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.

      You 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/nginx-selfsigned.key -out /etc/ssl/certs/nginx-selfsigned.crt

      Here’s a breakdown of what each part of this command does:

      • sudo: The sudo command allows members of the sudo group to temporarily elevate their privileges to that of another user (the superuser, or root user, by default). This is necessary in this case since we’re creating the certificate and key pair under the /etc/ directory, which can only be accessed by the root user or other privileged accounts.
      • 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 Nginx 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 stated previously, these options will create both a key file and a certificate. After running this command, you will be asked a few questions about your 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 like the following:

      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 of the /etc/ssl directory.

      While using OpenSSL, you should also create a strong Diffie-Hellman (DH) group, which is used in negotiating Perfect Forward Secrecy with clients.

      You can do this by typing:

      • sudo openssl dhparam -out /etc/nginx/dhparam.pem 4096

      This will take a while, but when it’s done you will have a strong DH group at /etc/nginx/dhparam.pem that will be used during configuration.

      Step 2 – Configuring Nginx to Use SSL

      Now that your key and certificate files under the /etc/ssl directory have been created, you’ll need to modify your Nginx configuration to take advantage of them.

      First, you will create a configuration snippet with the information about the SSL key and certificate file locations. Then, you will create a configuration snippet with a strong SSL setting that can be used with any certificates in the future. Finally, you will adjust your Nginx server blocks using the two configuration snippets you’ve created so that SSL requests can be handled appropriately.

      This method of configuring Nginx will allow you to keep clean server blocks and put common configuration segments into reusable modules.

      Creating a Configuration Snippet Pointing to the SSL Key and Certificate

      First, use your preferred text editor to create a new Nginx configuration snippet in the /etc/nginx/snippets directory. The following example uses nano.

      To properly distinguish the purpose of this file, name it self-signed.conf:

      • sudo nano /etc/nginx/snippets/self-signed.conf

      Within this file, you need to set the ssl_certificate directive to your certificate file and the ssl_certificate_key to the associated key. This will look like the following:

      /etc/nginx/snippets/self-signed.conf

      ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
      ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;
      

      When you’ve added those lines, save the file and exit the editor. If you used nano to edit the file, you can do so by pressing CTRL + X, Y, then ENTER.

      Creating a Configuration Snippet with Strong Encryption Settings

      Next, you will create another snippet that will define some SSL settings. This will set Nginx up with a strong SSL cipher suite and enable some advanced features that will help keep your server secure.

      The parameters you set can be reused in future Nginx configurations, so you can give the file a generic name:

      • sudo nano /etc/nginx/snippets/ssl-params.conf

      To set up Nginx SSL securely, we will adapt the recommendations from Cipherlist.eu. Cipherlist.eu is a useful and digestible resource for understanding encryption settings used for popular software.

      Note: These suggested settings from Cipherlist.eu 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 labeled “Yes, give me a ciphersuite that works with legacy / old software.” If desired, you can subsitute that list with the content of the next example code block.

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

      For your purposes, copy the provided settings in their entirety, but first, you will need to make a few small modifications.

      First, add your preferred DNS resolver for upstream requests. We will use Google’s (8.8.8.8 and 8.8.4.4) for this guide.

      Second, comment out the line that sets the strict transport security header. Before uncommenting this line, you should take a moment to read up on HTTP Strict Transport Security, or HSTS, and specifically about the “preload” functionality. Preloading HSTS provides increased security, but can also have far-reaching negative consequences if accidentally enabled or enabled incorrectly.

      Add the following into your ssl-params.conf snippet file:

      /etc/nginx/snippets/ssl-params.conf

      ssl_protocols TLSv1.3;
      ssl_prefer_server_ciphers on;
      ssl_dhparam /etc/nginx/dhparam.pem; 
      ssl_ciphers EECDH+AESGCM:EDH+AESGCM;
      ssl_ecdh_curve secp384r1;
      ssl_session_timeout  10m;
      ssl_session_cache shared:SSL:10m;
      ssl_session_tickets off;
      ssl_stapling on;
      ssl_stapling_verify on;
      resolver 8.8.8.8 8.8.4.4 valid=300s;
      resolver_timeout 5s;
      # Disable strict transport security for now. You can uncomment the following
      # line if you understand the implications.
      #add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
      add_header X-Frame-Options DENY;
      add_header X-Content-Type-Options nosniff;
      add_header X-XSS-Protection "1; mode=block";
      
      

      Because you’re using a self-signed certificate, the SSL stapling will not be used. Nginx will output a warning and disable stapling for our self-signed cert, but will then continue to operate correctly.

      Save and close the file by pressing CTRL + X then Y and ENTER when you are finished.

      Adjusting the Nginx Configuration to Use SSL

      Now that you have your snippets, you can adjust the Nginx configuration to enable SSL.

      We will assume in this guide that you are using a custom server block configuration file in the /etc/nginx/sites-available directory. This guide also follows the conventions from the prerequisite Nginx tutorial and use /etc/nginx/sites-available/your_domain for this example. Substitute your configuration filename as needed.

      Before moving forward, back up your current configuration file:

      • sudo cp /etc/nginx/sites-available/your_domain /etc/nginx/sites-available/your_domain.bak

      Now, open the configuration file to make adjustments:

      • sudo nano /etc/nginx/sites-available/your_domain

      Inside, your server block probably begins similarly to the following:

      /etc/nginx/sites-available/your_domain

      server {
              listen 80;
              listen [::]:80;
      
              root /var/www/your_domain/html;
              index index.html index.htm index.nginx-debian.html;
      
              server_name your_domain www.your_domain;
      
              location / {
                      try_files $uri $uri/ =404;
              }
      }
      
      

      Your file may be in a different order, and instead of the root and index directives, you may have some location, proxy_pass, or other custom configuration statements. This is fine since you only need to update the listen directives and include the SSL snippets. Then modify this existing server block to serve SSL traffic on port 443, and create a new server block to respond on port 80 and automatically redirect traffic to port 443.

      Note: Use a 302 redirect until you have verified that everything is working properly. After, you will change this to a permanent 301 redirect.

      In your existing configuration file, update the two listen statements to use port 443 and ssl, then include the two snippet files you created in previous steps:

      /etc/nginx/sites-available/your_domain

      server {
          listen 443 ssl;
          listen [::]:443 ssl;
          include snippets/self-signed.conf;
          include snippets/ssl-params.conf;
      
      root /var/www/your_domain/html;
              index index.html index.htm index.nginx-debian.html;
      
        server_name your_domain.com www.your_domain.com;
      
        location / {
                      try_files $uri $uri/ =404;
              }
      }
      
      
      

      Next, add a second server block into the configuration file after the closing bracket (}) of the first block:

      /etc/nginx/sites-available/your_domain.com

      
      server {
          listen 80;
          listen [::]:80;
      
          server_name your_domain.com www.your_domain.com;
      
          return 302 https://$server_name$request_uri;
      }
      

      This is a bare-bones configuration that listens on port 80 and performs the redirect to HTTPS. Save and close the file by pressing CTRL + X then Y and ENTER when you are finished editing it.

      Step 3 – Adjusting the Firewall

      If you have the ufw firewall enabled, as recommended by the prerequisite guide, you’ll need to adjust the settings to allow for SSL traffic. Luckily, Nginx registers a few profiles with ufw upon installation.

      You can review the available profiles by typing:

      A list like the following will appear:

      Output

      Available applications: Nginx Full Nginx HTTP Nginx HTTPS OpenSSH

      You can check the current setting by typing sudo ufw status:

      It will probably generate the following response, meaning that only HTTP traffic is allowed to the web server:

      Output

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

      To allow HTTPS traffic, you can update permissions for the “Nginx Full” profile and then delete the redundant “Nginx HTTP” profile allowance:

      • sudo ufw allow 'Nginx Full'
      • sudo ufw delete allow 'Nginx HTTP'

      After running sudo ufw status, you should receive the following output:

      Output

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

      This output confirms the adjustments to your firewall were successful and you are ready to enable the changes in Nginx.

      Step 4 – Enabling the Changes in Nginx

      With the changes and adjustments to your firewall complete, you can restart Nginx to implement the new changes.

      First, check that there are no syntax errors in the files. You can do this by typing sudo nginx -t:

      If everything is successful, you will get a result that says the following:

      Output

      nginx: [warn] "ssl_stapling" ignored, issuer certificate not found for certificate "/etc/ssl/certs/nginx-selfsigned.crt" nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

      Notice the warning in the beginning. As noted earlier, this particular setting generates a warning since your self-signed certificate can’t use SSL stapling. This is expected and your server can still encrypt connections correctly.

      If your output matches our example, your configuration file has no syntax errors. If this is the case, then you can safely restart Nginx to implement changes:

      • sudo systemctl restart nginx

      Now that the system has been restarted with the new changes, you can proceed to testing.

      Step 5 – Testing Encryption

      Now, you’re 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
      

      Depending on your browser, you will likely receive a warning since the certificate you created isn’t signed by one of your browser’s trusted certificate authorities,

      Nginx self-signed cert warning

      This warning 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:

      Nginx self-signed override

      At this point, you should be taken to your site. In our example, the browser address bar shows a lock with an “x” over it, which means that the certificate cannot be validated. It is still encrypting your connection. Note that this icon may differ, depending on your browser.

      If you configured Nginx with two server blocks, automatically redirecting HTTP content 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.

      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 Nginx configuration to make the redirect permanent.

      Open your server block configuration file again:

      • sudo nano /etc/nginx/sites-available/your_domain

      Find the return 302 and change it to return 301:

      /etc/nginx/sites-available/your_domain.com

          return 301 https://$server_name$request_uri;
      

      Save and close the file by pressing CTRL + X then Y and ENTER

      Check your configuration for syntax errors:

      When you’re ready, restart Nginx to make the redirect permanent:

      • sudo systemctl restart nginx

      After the restart, the changes will be implemented and your redirect is now permanent.

      Conclusion

      You have configured your Nginx server to use strong encryption for client connections. This will allow you to serve requests securely and prevent outside parties from reading your traffic. Alternatively, you may choose to use a self-signed SSL certificate that can be obtained from Let’s Encrypt, a certificate authority that installs free TLS/SSL certificates and enables encrypted HTTPS on web servers. Learn more from our tutorial on How To Secure Nginx with Let’s Encrypt on Ubuntu 20.04.



      Source link