How to secure the site

Steps to Configure and Secure a Website with Nginx and Streamlit

If you’re hosting a website or a web application using Nginx and Streamlit, here are the steps to adjust and secure the configuration:


1. Update the Nginx Configuration

Open the Nginx configuration file for your site and update the necessary settings.

Command:

sudo nano /etc/nginx/sites-available/yourwebsite.com

Update the Port and Add Proxy Settings:

location /your-path { proxy_pass http://localhost:8103; # Update with your desired port proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # WebSocket support proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }

Save and Exit:

  • Press CTRL+O to save.
  • Press CTRL+X to exit.

Test Nginx Configuration:

sudo nginx -t

Restart Nginx:

sudo systemctl restart nginx

2. Update the Service File for the Application

Ensure the service file correctly matches the port and path used in the Nginx configuration.

Navigate to the Service File:

cd /path/to/your/app nano yourapp.service

Example Service File:

[Unit] Description=Streamlit Application Service After=network.target [Service] User=yourusername Group=yourusername WorkingDirectory=/path/to/your/app Environment="PATH=/path/to/your/virtualenv/bin" ExecStart=/path/to/your/virtualenv/bin/streamlit run /path/to/your/app.py --server.port 8103 --server.baseUrlPath=/your-path [Install] WantedBy=multi-user.target

Save and Exit:

  • Press CTRL+O to save.
  • Press CTRL+X to exit.

Reload the Systemd Daemon:

sudo systemctl daemon-reload

Start the Service:

sudo systemctl start yourapp.service

Enable the Service to Start on Boot:

sudo systemctl enable yourapp.service

3. Secure Your Website

  • Enable SSL: Use Certbot to generate and install SSL certificates.
    sudo apt update sudo apt install certbot python3-certbot-nginx sudo certbot --nginx -d yourwebsite.com -d www.yourwebsite.com
  • Force HTTPS: Modify your Nginx configuration to redirect HTTP to HTTPS.
    server { listen 80; server_name yourwebsite.com www.yourwebsite.com; return 301 https://$host$request_uri; }

Reload Nginx:

sudo systemctl reload nginx

4. Verify the Setup

  • Check Service Status:
    sudo systemctl status yourapp.service
  • Test the Website: Visit https://yourwebsite.com/your-path to confirm everything is working.

This setup ensures your application is properly routed, secure with SSL, and configured for seamless operation.

Leave a Reply