Skip to content

Instantly share code, notes, and snippets.

@rousan
Last active July 17, 2021 14:22
Show Gist options
  • Save rousan/fe7408cd3dfc8e77c597137ea592ae06 to your computer and use it in GitHub Desktop.
Save rousan/fe7408cd3dfc8e77c597137ea592ae06 to your computer and use it in GitHub Desktop.

Install Nginx and Let's Encrypt on fresh VPS

/etc/systemd/system/neo.service

  • After creating a fresh VPS instance, Run:
$ sudo apt-get update && apt-get upgrade
$ sudo snap install core; sudo snap refresh core
$ sudo apt-get update && sudo apt-get upgrade -y
$ sudo apt-get install nginx -y
$ sudo systemctl start nginx
$ sudo systemctl enable nginx
$ sudo systemctl status nginx
  • Write config file at /etc/nginx/conf.d/<domain_name>.conf with the following content:
upstream my_http_servers {
    server 127.0.0.1:3001;
}
server {
    listen 80;
    server_name <domain_name>;
    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass         http://my_http_servers;
    }
}
  • Restart nginx server:
$ sudo systemctl restart nginx
  • Check if everything is working on http protocol.

  • Open 443 inbound/outbound port for the VPS instance.

  • Stop the nginx server to create the lets-encrypt certificate:

$ sudo systemctl stop nginx
  • Install the lets-encrypt SSL provider:
$ sudo snap install --classic certbot
$ sudo ln -s /snap/bin/certbot /usr/bin/certbot
  • Generate SSL certificate:
$ sudo certbot certonly --standalone -d <domain_name>
$ sudo certbot renew --dry-run
  • Open /etc/nginx/conf.d/<domain_name>.conf file and replace it with the following content:
upstream my_http_servers {
    server 127.0.0.1:3001;
}

server {
    listen 443;
    server_name <domain_nam>;

    ssl on;
    ssl_certificate /etc/letsencrypt/live/<domain_nam>/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/<domain_nam>/privkey.pem;

    location / {
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   Host      $http_host;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass         http://my_http_servers;
    }
}

server {
    listen 80;

    server_name <domain_nam>;
    return 301 https://<domain_nam>$request_uri;
}
  • Restart nginx server:
$ sudo systemctl restart nginx
  • Now, check if everything is working on https protocol.

References

  1. https://medium.com/@utkarsh_verma/configure-nginx-as-a-web-server-and-reverse-proxy-for-nodejs-application-on-aws-ubuntu-16-04-server-872922e21d38
  2. https://medium.com/@samanbaboli/how-to-load-balancing-nodejs-apps-using-nginx-a3b4ceb7c782
  3. https://tecadmin.net/install-lets-encrypt-create-ssl-ubuntu/
  4. https://tecadmin.net/install-lets-encrypt-create-ssl-ubuntu/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment