nick
nick

Reputation: 1178

Redirect nginx www to https

Hi so I'm a complete beginner at using nginx. I have my website up and running and currently it redirects http to https. However if I vist www.example.com nginx will redirect it to https://www.example.com. How can I make it so www gets redirected to https?

My nginx config looks like:

    server {
        root /var/www/html;
        index index.html index.htm index.nginx-debian.html;
        server_name _;
        location / {
                try_files $uri $uri/ =404;
        }
}

upstream my_nodejs_upstream {
 server 127.0.0.1:5000;
 keepalive 64;
}

server {
        root /var/www/html;

        index index.html index.htm index.nginx-debian.html;
      server_name example.com; # managed by Certbot

        location / {
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header Host $http_host;
                proxy_set_header X-NginX-Proxy true;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection upgrade;
                proxy_max_temp_file_size 0;
                proxy_pass http://my_nodejs_upstream/;
                proxy_redirect off;
                proxy_read_timeout 240s;
        }

        location /api {
                proxy_pass http://localhost:3001;


    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


        listen 80 ;
        listen [::]:80 ;
    server_name example.com;
    return 404; # managed by Certbot


}

Upvotes: 0

Views: 102

Answers (1)

Venkatesh A
Venkatesh A

Reputation: 2474

Thing to do to achieve http -> https redirection at www.

  1. Add www.<your_domain> to your server name in your server block like below:
server_name example.com; # managed by Certbot

to

server_name example.com www.example.com; # managed by Certbot
  1. Make sure that www.<your_domain>'s A record (create subdomain www.<your_domain> if not available) points to the server's ip from your domain's dns.
  2. Regenerate the certificates for the new server block.

Now you will have redirection for both http://<your_domain> and http://www.<your_domain> to https

Upvotes: 1

Related Questions