Introduction

Configuring Nginx properly on EC2 instances is crucial for managing web traffic and deploying multiple applications. This guide walks through key configuration scenarios I’ve encountered while setting up reverse proxies on Amazon Linux instances. Whether you’re routing traffic to different apps or setting up SSL, these practical examples will help you get started.

Nginx Architecture


Installation

For Amazon Linux:

sudo yum install nginx certbot python3-certbot-nginx

For Ubuntu:

sudo apt install nginx certbot python3-certbot-nginx

Pro Tip: The certbot package will help you set up Let’s Encrypt SSL certificates later!

Configuration

All configuration files live in /etc/nginx/conf.d/. Create a new file like servers.conf for your custom rules.

Config Directory Structure

Nginx Config Directory

Default Server Setup

Handle unmatched requests with these options:

  1. Block All Traffic (403 Forbidden):
server {
    listen 80 default*server;
    server_name *;
    return 403;
}
  1. Default 404 Page:
server {
    listen 80 default_server;
    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
  1. Redirect to Another Site:
server {
    listen 80 default_server;
    return 301 https://yourfallbacksite.com;
}

Reverse Proxy Configuration

Route traffic based on URL paths:

server {
    listen 80;

    location /app1 {
        proxy_pass http://localhost:8501;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /app2 {
        proxy_pass http://localhost:3000;
        include /etc/nginx/proxy_params;
    }
}

Note: Create a proxy_params file for reusable proxy settings!

Special Case: Streamlit Deployment

Required for WebSocket connections:

server {
    listen 80;
    server_name streamlit.yourdomain.com;

    location / {
        proxy_pass http://localhost:8501/;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        include /etc/nginx/proxy_params;
    }
}

Conclusion

With these configurations, you can:

  1. Handle unexpected requests gracefully
  2. Route traffic to multiple applications
  3. Support modern web apps with WebSockets

Next steps:

  • Set up SSL using Certbot
  • Configure access logging
  • Implement rate limiting

References