How to add SSL and HTTPS to WordPress

SSL certificates makes your website more trustworthy to readers and it highly likely that your will spend more time or trust your content more when he sees ‘Secure’ in green in address bar. Not just this, search engine provider give higher rank to secure sites as compared to non secure websites. You can follow below steps to make your WordPress website “Secure” at not extra cost.

Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free TLS/SSL certificates,

Step#1 Install Certbots

sudo add-apt-repository ppa:certbot/certbot

Update packages

sudo apt-get update

Install certbost nginx package

sudo apt-get install python-certbot-nginx

Step#2 Configure NGINX

Most likely this is already configured. Just ensure your host names are updated corrected as below.

server_name example.com www.example.com;

Verify NGINX syntax and restart it.

sudo nginx -t

sudo systemctl reload nginx

Step#3 Allow HTTPS through firewall.

sudo ufw allow 'Nginx Full'

Once this is done, you can check what all is allowed

sudo ufw status

Step#4 Obtain SSL Certificate.

Use following command to obtain SSL certificate. It will ask for email ID where notifications will be sent.

sudo certbot --nginx -d example.com -d www.example.com
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Enter email address (used for urgent renewal and security notices) (Enter 'c' to
cancel):

Once your enter email ID and hit enter, it will ask for few usual confirmations.

Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org

-------------------------------------------------------------------------------
Please read the Terms of Service at
https://letsencrypt.org/documents/LE-SA-v1.2-November-15-2017.pdf. You must
agree in order to register with the ACME server at
https://acme-v01.api.letsencrypt.org/directory
-------------------------------------------------------------------------------
(A)gree/(C)ancel: A

-------------------------------------------------------------------------------
Would you be willing to share your email address with the Electronic Frontier
Foundation, a founding partner of the Let's Encrypt project and the non-profit
organization that develops Certbot? We'd like to send you email about EFF and
our work to encrypt the web, protect its users and defend digital rights.
-------------------------------------------------------------------------------
(Y)es/(N)o: Y

Once this is done, it will ask about redirect . Please find below sample example for this site.

Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Starting new HTTPS connection (1): acme-v01.api.letsencrypt.org
Obtaining a new certificate
Performing the following challenges:
http-01 challenge for techtrekking.net
http-01 challenge for www.techtrekking.net
Waiting for verification...
Cleaning up challenges
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/techtrekkingnet
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/techtrekkingnet

Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/techtrekkingnet
Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/techtrekkingnet

-------------------------------------------------------------------------------
Congratulations! You have successfully enabled https://techtrekking.net and
https://www.techtrekking.com

You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=techtrekking.net
https://www.ssllabs.com/ssltest/analyze.html?d=www.techtrekking.net
-------------------------------------------------------------------------------

IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/techtrekking.net/fullchain.pem
Your key file has been saved at:
/etc/letsencrypt/live/techtrekking.net/privkey.pem
Your cert will expire on 2018-07-30. 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"
- 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

 

Step#5 Configuring WordPress

Once you have this these changes, making sure your WordPress is compatible with this changes is must. Although  I did not face any issue even after not making changes in WordPress, I recommend you do it.

WordPress Address Configuration for SSL

Although it is not mandatory, please restart your NGINX server. Once done, when you access your website, you will see “Secure” in green. Just like below.

WordPress SSL

This SSL certificate is valid for 90 days, please refer to this post to see how to set up cron job renewal of Let’s Encrypt SSL Certificate

How to install wordpress on Ubuntu 16.04

Here is quick reference that I created for myselft for creating local wordpress blog installation. Hoep it helps you as well.

  • Installation

Make sure you have following softwares installed on your local machine

  1. MySQL
  2. NGINX
  • Configure MySQL

Create user for wordpress

mysql -u root -p
mysql> CREATE DATABASE localwordpress DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
mysql> GRANT ALL ON localwordpress.* TO 'localwordpresssuser'@'localhost' IDENTIFIED BY 'password';
mysql> FLUSH PRIVILEGES;
mysql> exit;
  • Download  WordPress.

curl -O https://wordpress.org/latest.tar.gz
tar xzvf latest.tar.gz
cp wordpress/wp-config-sample.php wordpress/wp-config.php
mkdir wordpress/wp-content/upgrade
sudo cp -a wordpress  /var/www/wordpress1

After moving WordPress folder to required path, you need to change few folder permissions.

sudo chmod g+w /var/www/html/wp-content
sudo chmod -R g+w /var/www/html/wp-content/themes
sudo chmod -R g+w /var/www/html/wp-content/plugins
sudo chown -R www-data:www-data /var/www/html
  • Configure WordPress

Open wp-config.php file and make following changes

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'localwordpress');

/** MySQL database username */
define('DB_USER', 'localwordpresssuser');

/** MySQL database password */
define('DB_PASSWORD', 'password_here');

/** MySQL hostname */
define('DB_HOST', 'password');

/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');

/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');

Visit following link for generate AUTH KEY and other remaining fields

https://api.wordpress.org/secret-key/1.1/salt/

simply copy paste values displayed on above link  into config.php file at appropriate location. Here is the sample. (Please don’t copy paste below values into your installation)

define('AUTH_KEY',         'Johd+fp5c.esU?J26hZb8^6Gi GAL+^Abs-{k4%g0G4IEGVKlZ`|MEk4B;W++%s*');
define('SECURE_AUTH_KEY',  '_J}pBRjcek6f+wj*BNF}lPu-xNX$^.+`nIx|*kg-YjY+v)%Qi<J`pI?|zE/BIa<U');
define('LOGGED_IN_KEY',    '2.T%wJpUwsSeZQV?K,R)7$u }yl]rfLt|.gg,uI.SP&U>u_7q+*uH2+Gy4}-AmYC');
define('NONCE_KEY',        '~^T R=oy/Ej`>q8&FP7rPM1vZ%;}*@oz7^b~~>>Clw{.LGYdbDjV$-t<U5/(&;M7');
define('AUTH_SALT',        'Nn?`[;?9=niA=Jun:ikXi(BR%%Y7MYVtMd+,a&_ZKQei3S ;Z8XteX{=f8~~=D~p');
define('SECURE_AUTH_SALT', 'WCRf7Un/.BX9z~_4dt}!-k$<Y02mm=fKEvHo;5{]!s9=w/x/@9-,Q?ib-jMM#47/');
define('LOGGED_IN_SALT',   '$~+K5U>rd3_B#+X*^G2hlBTnD:)W](rer%VMS #G8jJ^f(5Gr@.aF:6`hg~:OkS(');
define('NONCE_SALT',       'xdtH,{ir(-I5|/NIHaD^eFu.pKCIC-5!Gn`YBDq#?bRfhI5,-c,;?^^<6V%P04iD');

Also add FS_METHOD  after “define (‘WP_DEBUG’, false);”. It should look as below

define('WP_DEBUG', false);
define('FS_METHOD', 'direct');
  • Troubleshooting

I got error “Authentication is needed to run ‘/bin/cp’ as the super user” while saving wp-config.php file.

Its not a big deal. Simply go to terminal and run following commands

sudo chmod 777 projectname
sudo chown $USER -R projectname/
  • Configure nginx

  • You need to configure nginx so that typed url will direct to correct installation directory. Following is the sample code. You can copy this as is but make sure you change the server_name parameter to your domain name.Create following file in folder /etc/nginx/sites-available/. You name is as you with but for easy reference, add name of domain in the file name.
    server {
    listen 80;
    listen [::]:80;
    
    root /var/www/wordpress1;
    index index.html index.htm index.nginx-debian.html;
    
    server_name localwordpress1.com www.localwordpress1.com;
    
    location / {
    #try_files $uri $uri/ =404;
    # original content
    try_files $uri /index.php$is_args$args;
    #try_files $uri $uri/ /index.php$is_args$args;
    }
    
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    
    # With php7.0-cgi alone:
    #fastcgi_pass 127.0.0.1:9000;
    # With php7.0-fpm:
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
    
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    # deny all;
    #}
    }

    copy this file to sites-enabled folder using following command and restart nginx

    $sudo ln -s /etc/nginx/sites-available/wordpress1.com /etc/nginx/sites-enabled/
    $sudo nginx -t
    $sudo systemctl restart nginx

    Considering we need to access local installation on custom url, that url need to point to localhost. This needs to be changed in host file.

    sudo nano /etc/hosts
    127.0.1.1 localwordpress1.com
  • Access your installation # localwordpress1.com
install wordpress ubuntu 16.04
install wordpress ubuntu 16.04

ngnix redirect non www to www

if you want to redirect non www to www domain you need to add one more serverblock at the top of your nginx config file as beloww

server {  
        listen 80;
        server_name techtrekking.net;
        # $scheme will get the http protocol
        return 301 $scheme://www.techtrekking.net$request_uri;
}

This works for normal website as well as ghost blog.
For example if you type techtrekking.net or www.techtrekking.net it will get redirected to www.techtrekking.net.

Sample server block. THis serves following purpose

  • redirect non www to www
  • add blog in subfolder /blog
server {  
        listen 80;
        server_name yoursite.com;
        # $scheme will get the http protocol
        return 301 $scheme://www.yoursite.com$request_uri;
}

server {  
        listen 80;
        listen [::]:80;

        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;

        server_name techtrekking.com www.techtrekking.com;

        location / {
                proxy_pass http://yoursite:3000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
        }

        location /blog {
                proxy_pass http://yoursite:3100;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;

        }


        location ~ /.well-known {
                allow all;
        }

}