Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

alexmansour's avatar

Nginx redirects. non-www to www

Hello,

How we can redirect none www to www when SSL installed.

Thank you.

0 likes
4 replies
bashy's avatar
bashy
Best Answer
Level 65

From my blog post about redirecting to certain versions: https://bashy.im/blog/nginx-redirect-to-https-with-without-www-subdomain

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

        server_name www.example.com example.com;

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

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        ssl_certificate /etc/nginx/certs/example.crt;
        ssl_certificate_key /etc/nginx/certs/example.key;

        # Ciphers and protocols
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Excludes SSLv2/3
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"; # Current at the time of Feb 2016
        ssl_prefer_server_ciphers on;

        server_name example.com;

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

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        ssl_certificate /etc/nginx/certs/example.crt;
        ssl_certificate_key /etc/nginx/certs/example.key;

        # Ciphers and protocols
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Excludes SSLv2/3
        ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH"; # Current at the time of Feb 2016
        ssl_prefer_server_ciphers on;

        server_name www.example.com;

        [...]
}
1 like
alexmansour's avatar

@bashy Thank you.

Got it, I had to put all the three as each has it's own different job.

bashy's avatar

Yes you need all three (or last two if you only listen on 443). The first block redirects any HTTP version of your site to the www HTTPS version. The second block is to redirect from HTTPS non-www to www. Last is your main working area and will serve the files.

You're welcome. Mark that as correct if it solves your issue.

2 likes

Please or to participate in this conversation.