Securing Ethereum JSON-RPC API with Nginx Password Protection

·

This guide is tailored for Ethereum smart contract application developers, focusing on securely running an Ethereum node behind password protection for safe internet access.

Why Secure Your Ethereum Node?

Popular Ethereum implementations like Go Ethereum (geth), Parity, and cpp-ethereum power decentralized applications (DApps). These DApps—client-side JavaScript webpages—connect to Ethereum nodes via the JSON-RPC API over HTTP.

However, exposing this API to the public internet poses risks:

HTTP Basic Authentication with Nginx

Overview

HTTP Basic Authentication is a simple yet effective method to restrict API access. While not ultra-secure, it’s ideal for:

Step-by-Step Setup

1. Install Nginx

On Ubuntu 14.04+:

sudo apt install nginx apache2-utils

2. Configure Nginx

Edit /etc/nginx/sites-enabled/default to proxy requests to localhost:8545 (geth’s default port):

server {
    listen 80 default_server;
    server_name demo.example.com;

    # Password-protected JSON-RPC endpoint
    location /eth {
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/protected.htpasswd;
        proxy_pass http://localhost:8545;
    }

    # Serve DApp files
    location / {
        root /usr/share/nginx/html;
        index index.html;
        auth_basic "Restricted Access";
        auth_basic_user_file /etc/nginx/protected.htpasswd;
    }
}

3. Create Authentication Credentials

Generate a password file:

sudo htpasswd -c /etc/nginx/protected.htpasswd demo

4. Configure geth

Run geth as a background process:

screen
geth # Add your command-line parameters

Exit with CTRL+A, D.

👉 Explore advanced geth configurations

5. Deploy Your DApp

Update web3.js to use the /eth endpoint:

function getRPCURL() {
    return window.location.href.includes("demo.example.com") 
        ? "http://demo.example.com/eth" 
        : "http://localhost:8545";
}
web3.setProvider(new web3.providers.HttpProvider(getRPCURL()));

6. Restart Nginx

service nginx stop && service nginx start

Troubleshooting


FAQ

Why use Nginx instead of geth’s built-in features?

Nginx provides robust, battle-tested security layers without bloating the node software.

Can I use this for production?

For high-stakes environments, combine HTTP Basic Auth with HTTPS (TLS) and rate limiting.

How do I update passwords?

sudo htpasswd /etc/nginx/protected.htpasswd newuser

Advanced Deployment Tips

Automate DApp Deployment

Use this shell script to sync files and set permissions:

#!/bin/bash
REMOTE="your-server"
npm run build
rsync -a -e "ssh" --rsync-path="sudo rsync" dist/* \
    --chown www-data:www-data $REMOTE:/usr/share/nginx/html/

👉 Learn more about secure deployments


Final Notes