DEV Community

Ravi Agheda
Ravi Agheda

Posted on • Edited on

How to redirect the domain to the port number using Nginx and set up SSL?

Nginx Configuration Setup

Install Nginx

sudo apt update
sudo apt install nginx
Enter fullscreen mode Exit fullscreen mode

Link port with domain

Open this file in nano or vim /etc/nginx/nginx.conf

http{
  server{
    listen 80;
    server_name DOAMIN.com www.DOMAIN.com;
    location / {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header Host $http_host;
      proxy_pass http://<IP_ADDRESS>;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

After updating nginx.conf apply this commands
Test nginx.conf sudo nginx -t
Restart nginx service sudo systemctl restart nginx or sudo service nginx restart
Check nginx status sudo systemctl status nginx or sudo service nginx status

Issue ssl certificate from certbot

Ref: https://www.nginx.com/blog/using-free-ssltls-certificates-from-lets-encrypt-with-nginx/

Install certbot

sudo apt-get update
sudo apt-get install certbot
sudo apt-get install python-certbot-nginx
Enter fullscreen mode Exit fullscreen mode

Obtain the SSL/TLS Certificate

sudo certbot --nginx -d example.com -d www.example.com

It'll handle the required modification for https in nginx.conf

Automatically Renew Let’s Encrypt Certificates

crontab -e
0 12 * * * /usr/bin/certbot renew --quiet

Manually setup SSL and https configuration on nginx

http{
  server{
    listen 80;
    server_name spotcodes.in www.spotcodes.in;
    return 301 https://$server_name$request_uri;
  }

  server {
    listen 443 ssl;
    server_name spotcodes.in www.spotcodes.in;

    ssl_certificate /etc/letsencrypt/live/spotcodes.in/cert.pem;
    ssl_certificate_key /etc/letsencrypt/live/spotcodes.in/privkey.pem;

    location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;
    proxy_pass http://3.83.202.107:2001;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Test SSL certificate installation

https://www.experte.com/ssl-check

Usefull links and credits

Top comments (0)