How to redirect from non-www to www with nginx on Ubuntu ?

Published: August 29, 2022

Updated: December 09, 2022

Tags: NGINX;

DMCA.com Protection Status

Example of how to redirect from non-www to www with nginx on Ubuntu:

Redirect to https

On Ubuntu go to

/etc/nginx/sites-available/

and open the file associated with your website:

vi mysite

Assuming that you site use https, the first step is to redirect http://mysite.com and http://www.mysite.com urls to https://www.mysite.com, to do that

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

Note if you are not using https for your website just do

server {
    listen 80;
    listen [::]:80;
    server_name mysite.com;
    return 301 http://www.mysite.com$request_uri;
}

and stop here.

Redirect https://mysite.com to https://www.mysite.com

Next step. redirect https://mysite.com to https://www.mysite.com

server {
    listen 443 ssl;
    server_name mysite.com;

    ssl_certificate /root/ssl_certificates/mysite.crt;
    ssl_certificate_key /root/ssl_certificates/mysite.com.key;

    return 301 https://www.mysite.com$request_uri;
}

Create server request for https://www.mysite.com

Final step, Create server request for https://www.mysite.com

server {
    listen 443 ssl;
    server_name www.mysite.com;

    ssl_certificate /root/ssl_certificates/mysite.crt;
    ssl_certificate_key /root/ssl_certificates/mysite.com.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    }

Complete nginx file

So, the file mysite located under /etc/nginx/sites-available/ should be similar to:

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

server {
    listen 443 ssl;
    server_name mysite.com;

    ssl_certificate /root/ssl_certificates/mysite.crt;
    ssl_certificate_key /root/ssl_certificates/mysite.com.key;

    return 301 https://www.mysite.com$request_uri;
}


server {
    listen 443 ssl;
    server_name www.mysite.com;

    ssl_certificate /root/ssl_certificates/mysite.crt;
    ssl_certificate_key /root/ssl_certificates/mysite.com.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    }