Need 1 nginx vhost redirecting non-www to www and http to https

Discussion in 'Server Operation' started by Ovidiu, Nov 13, 2016.

  1. Ovidiu

    Ovidiu Active Member

    Hi there,

    I've struggled with this for hours now and no matter what i tried its not 100% working. I got a free security certificate from letsencrypt for www.knightsenglish.com but it is only valid for www.knightsenglish.com so if you browse there without www its invalid.

    This all should work like this:
    browsing to http://knightsenglish.com or http://www.knightsenglish.com or https://knightsenglish.com
    should all redirect you to https://www.knightsenglish.com

    Here is what I got so far: /etc/nginx/sites-enabled/knightsenglish.com.conf
    Code:
    server {
            # redirecting http port 80 to https port 443 and adding www
            listen 80;
            server_name www.knightsenglish.com knightsenglish.com;
            return 301 https://www.knightsenglish.com$request_uri;
    }
    server
    {
            listen 443 ssl;
            ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
            ssl_certificate /etc/ssl/private/www.knightsenglish.com.crt;
            ssl_certificate_key /etc/ssl/private/www.knightsenglish.com.key;
            server_name www.knightsenglish.com;
    and this is not working: https://knightsenglish.com its not adding WWW.

    I could easily get a certificate for the non-www version, would that be easier? I'm looking for an elegant solution here.
    Do I possibly need 4 server declarations? 2 for each www and non-www (http+https)?
     
    Last edited: Nov 13, 2016

Share This Page