Technical Blog

DNS Setup, SSL, and HTTP Configuration for Flask Application

Published on March 16, 2024 8 min read

After deploying your Flask application on AWS EC2, the next crucial step is setting up a custom domain, configuring DNS, and securing your application with SSL. This guide walks you through the entire process.

Prerequisites

  • A deployed Flask application on AWS EC2
  • A registered domain name
  • Access to your domain's DNS settings

1. DNS Configuration

First, let's configure your domain's DNS settings:

  • Log in to your domain registrar's website
  • Navigate to DNS management
  • Add the following records:
# A Record
Type: A
Host: @
Value: your-ec2-ip-address
TTL: 300

# CNAME Record (for www subdomain)
Type: CNAME
Host: www
Value: your-domain.com
TTL: 300

2. Install Certbot for SSL

sudo apt update
sudo apt install certbot python3-certbot-nginx -y

3. Configure Nginx for Your Domain

Update your Nginx configuration:

sudo nano /etc/nginx/sites-available/myflaskapp

Add the following configuration:

server {
    listen 80;
    server_name your-domain.com www.your-domain.com;

    location / {
        proxy_pass http://unix:/home/ubuntu/your-repo/myflaskapp.sock;
        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;
    }
}

4. Obtain SSL Certificate

sudo certbot --nginx -d your-domain.com -d www.your-domain.com

Follow the prompts to:

  • Enter your email address
  • Agree to terms of service
  • Choose whether to redirect HTTP to HTTPS

5. Verify SSL Configuration

sudo nginx -t
sudo systemctl restart nginx

6. Set Up Auto-Renewal

Certbot creates a timer for automatic renewal. Verify it with:

sudo systemctl status certbot.timer

Additional Security Measures

  • Configure SSL parameters for better security
  • Add security headers
  • Enable HSTS

Add these to your Nginx configuration:

server {
    # ... existing configuration ...

    # SSL configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;

    # Security headers
    add_header Strict-Transport-Security "max-age=31536000" always;
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";
}

Conclusion

Your Flask application should now be accessible via HTTPS at your custom domain. Remember to:

  • Monitor SSL certificate expiration
  • Regularly update security configurations
  • Keep Nginx and Certbot updated
  • Implement proper logging for SSL/TLS issues