Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save coutinhomarco/77336a4cac563ea7fa670e10d09222ec to your computer and use it in GitHub Desktop.
Save coutinhomarco/77336a4cac563ea7fa670e10d09222ec to your computer and use it in GitHub Desktop.
Step-by-Step Guide to Setting Up an EC2 Instance with Nginx and SSL

Step-by-Step Guide to Setting Up an EC2 Instance with Nginx and SSL

1. Create an EC2 Instance

  • Launch an Amazon EC2 instance using your preferred AMI (Amazon Machine Image).

2. Configure Security Group

  • Create a new security group.
  • Allow access to ports 80 (HTTP) and 443 (HTTPS) from all IP addresses.
  • Allow SSH access only from your personal IP address for security.

3. Connect to Your EC2 Instance via SSH

  • Use the SSH command to connect:
    ssh -i "your-key.pem" ec2-user@your-ec2-ip-address

4. Install Nginx on EC2

Execute the following commands to install Nginx:

sudo wget http://nginx.org/keys/nginx_signing.key
sudo apt-key add nginx_signing.key
sudo apt-get update
sudo apt-get install nginx
sudo systemctl start nginx.service
# Optionally, check the status of Nginx:
sudo systemctl status nginx.service

5. Install Certbot and Configure SSL

Install Certbot and generate SSL certificates:

sudo snap install core; sudo snap refresh core
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot
sudo certbot certonly --nginx
# Note the path where your SSL certificates are stored.

6. Configure Nginx to Use SSL

Set up your Nginx server block to use HTTPS:

  1. Navigate to the Nginx configuration directory and create a new configuration file:
    cd /etc/nginx/conf.d
    sudo touch default.conf
    sudo nano default.conf
  2. Edit the default.conf file to include the following:
    server {
        listen 443 ssl;
        server_name your-domain.com;
    
        ssl_certificate /etc/letsencrypt/live/your-domain.com/fullchain.pem; # Adjust path as necessary
        ssl_certificate_key /etc/letsencrypt/live/your-domain.com/privkey.pem; # Adjust path as necessary
    
        add_header Strict-Transport-Security "max-age=31536000";
    
        location / {
            proxy_pass http://127.0.0.1:PORT; # Replace PORT with the port number of your application
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    • Replace your-domain.com with your actual domain name.
    • Replace PORT with the port number where your application is running.

Final Steps

  • Restart Nginx to apply the changes:
    sudo systemctl restart nginx
  • Ensure your firewall and security group settings allow traffic on port 443.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment