Table of Contents
- Introduction
- Preparation
Setting Up the Raspberry Pi
- 3.1 Installing the Operating System
- 3.2 Updating and Upgrading the System
- 3.1 Installing the Operating System
- Installing the Nginx Web Server
- Configuring the Firewall (UFW)
Setting Up Dynamic DNS (DDNS)
- 6.1 Registering a Cloudflare Account and Adding Your Domain
- 6.2 Obtaining an API Token and Zone ID
- 6.3 Adding a DNS Record
- 6.4 Writing a Script to Automatically Update Your IP
- 6.1 Registering a Cloudflare Account and Adding Your Domain
- Configuring Port Forwarding on Your Router
Deploying Your Static Website
- 8.1 Creating a Simple HTML Page
- 8.2 Configuring Nginx to Serve Your Website
- 8.1 Creating a Simple HTML Page
- Installing Certbot and Setting Up HTTPS Certificates
- Testing and Troubleshooting
- Conclusion
1. Introduction
So, you've decided to host your own website from your basement using a Raspberry Pi? Excellent choice! Not only will you save money on hosting fees, but you'll also become the tech wizard among your friends. In this guide, we'll walk you through every step—from setting up your Raspberry Pi to having a shiny, secure website that says "Hello, I'm Ken" to the world.
and download Raspberry Pi Imager suitable for your operating system.
- Click on "Choose Storage" and select your microSD card.
Optional but Highly Recommended: Enable SSH and Set Wi-Fi
- Click on the gear icon to access advanced settings.
- Set a username and password (make sure to remember them).
- If you're using Wi-Fi, enter your SSID and password.
- Enable SSH by checking the box "Enable SSH".
Step 5: Write the OS
- Click on "Write" and confirm that you want to erase the card.
- Wait patiently as the OS is written to the card.
Finding Your Router's IP Address
If you're unsure of your router's IP address, you can find it using the command line:
Windows:
ipconfig
Look for the "Default Gateway" under your network adapter.
macOS/Linux:
route -n
or
netstat -nr
Find the default gateway address.
Step 3: Connect via SSH
- Open your SSH client.
- For Windows (PuTTY or Terminal):
Host Name:your_username@your_pi_ip_address(e.g.,[email protected])
Port:22
- For macOS/Linux (Terminal):
ssh your_username@your_pi_ip_address
- Enter your password when prompted (the password won't be visible as you type).
Example using SSH on Windows Terminal:
Optional but Recommended: Set Up SSH Keys
Setting up SSH keys allows you to connect to your Pi without entering a password each time.
On your PC terminal:
ssh-keygen -t rsa
- Press
Enterthree times to accept the default settings.
- Open
id_rsa.pubwith a text editor and copy its content. - On your Raspberry Pi terminal, create the
.sshdirectory and theauthorized_keysfile:
mkdir ~/.ssh
nano ~/.ssh/authorized_keys
- Paste the copied public key into the file.
- Press
Ctrl + X, thenY, thenEnterto save and exit.
5. Configuring the Firewall (UFW)
Protect your Raspberry Pi from unauthorized access.
Step 1: Install UFW
sudo apt install ufw -y
Step 2: Allow SSH and Web Traffic
- Allow SSH:
sudo ufw allow ssh
- Allow HTTP and HTTPS traffic:
sudo ufw allow 'Nginx Full'
Step 3: Set Default Rules and Enable the Firewall
- Deny all incoming traffic (except allowed):
sudo ufw default deny incoming
- Enable the firewall:
sudo ufw enable
- Type
ywhen prompted.
Step 4: Check the Status
sudo ufw status verbose
- You should see rules for OpenSSH and Nginx.
and create a free account.
Step 2: Add Your Domain
- In the Account Home, click "Add site".
- Enter your domain name (e.g.,
example.com).
Step 4: Update Your Nameservers
- Cloudflare will provide nameservers (e.g.,
bob.ns.cloudflare.comandlisa.ns.cloudflare.com). - Log in to your domain registrar (where you bought the domain).
- Replace the existing nameservers with the ones provided by Cloudflare.
to check the status.
6.2 Obtaining an API Token and Zone ID
An API token allows your Pi to communicate with Cloudflare to update DNS records, and the Zone ID uniquely identifies your domain.
Step 1: Create an API Token
- In Cloudflare, click on your profile icon and select "My Profile".
Token Name:DDNS Update Token
Permissions:
- Zone - DNS - Edit
- Zone - Zone - Read
Zone Resources: Include -> Specific Zone -> Your domain (e.g.,example.com)
Step 3: Create and Copy the Token
- Click "Continue to summary", then "Create Token".
- Copy the token and store it securely.
Step 4: Obtain the Zone ID
- In your Cloudflare Account Home, click on your domain name (e.g.,
example.com). - Scroll down; at the bottom right, you'll find your Zone ID.
6.4 Writing a Script to Automatically Update Your IP
Let's automate the IP update process.
Step 1: Create a Directory for Your Script
mkdir ~/Documents/DDNS
cd ~/Documents/DDNS
nano update_dns.py
Step 2: Write the Python Script
#!/usr/bin/env python3
import requests
import json
import os
# Cloudflare API credentials
auth_key = "your_api_token_here" # Replace with your actual API token
record_name = "your_domain.com" # Replace with your domain
zone_id = "your_zone_id_here" # Replace with your Zone ID
ip_file = "ip.txt"
headers = {
"Authorization": f"Bearer {auth_key}",
"Content-Type": "application/json"
}
def get_record_id():
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records?name={record_name}"
response = requests.get(url, headers=headers)
response_data = response.json()
if response_data.get("success"):
return response_data["result"][0]["id"]
else:
print("Failed to fetch record ID")
return None
def get_current_ip():
response = requests.get("http://ipv4.icanhazip.com")
return response.text.strip()
def update_dns_record(record_id, ip):
url = f"https://api.cloudflare.com/client/v4/zones/{zone_id}/dns_records/{record_id}"
data = {
"type": "A",
"name": record_name,
"content": ip,
"ttl": 120,
"proxied": False
}
response = requests.put(url, headers=headers, json=data)
return response.json()
def main():
current_ip = get_current_ip()
if os.path.exists(ip_file):
with open(ip_file, "r") as file:
last_ip = file.read().strip()
else:
last_ip = None
if last_ip == current_ip:
print("IP has not changed")
else:
print("IP has changed, updating DNS record...")
record_id = get_record_id()
if not record_id:
print("Error: Could not retrieve the DNS record ID.")
return
result = update_dns_record(record_id, current_ip)
if result.get("success"):
print(f"DNS record updated successfully to IP: {current_ip}")
with open(ip_file, "w") as file:
file.write(current_ip)
else:
print("Failed to update DNS record")
print(result)
if __name__ == "__main__":
main()
- Replace:
auth_keywith your API token.
record_namewith your domain.
zone_idwith your Zone ID.
Step 3: Save and Exit
- Press
Ctrl + O, thenEnterto save. - Press
Ctrl + Xto exit.
Step 4: Make the Script Executable
chmod +x update_dns.py
Step 5: Test the Script
./update_dns.py
- Check if the DNS record is updated on Cloudflare.
Step 3: Locate Port Forwarding Settings
- Go to the "Port Forwarding", "NAT", or "Virtual Servers" section.
If everything works, congratulations! You've passed the hardest part.
8. Deploying Your Static Website
Let's replace the default Nginx page with your own content.
8.1 Creating a Simple HTML Page
Create a simple webpage that says "Hello, I'm Ken".
Step 1: Create an HTML File
- Create a new directory:
sudo mkdir /var/www/ken
- Create the
index.htmlfile:
nano /var/www/ken/index.html
- Paste the following content:
<!DOCTYPE html>
<html>
<head>
<title>Hello, I'm Ken</title>
</head>
<body>
<h1>Hello, I'm Ken</h1>
<p>Welcome to my awesome Raspberry Pi hosted website!</p>
</body>
</html>
Step 2: Save and Exit
- Press
Ctrl + O, thenEnterto save. - Press
Ctrl + Xto exit.
8.2 Configuring Nginx to Serve Your Website
Step 1: Create a New Nginx Server Block
- Create a new configuration file:
sudo nano /etc/nginx/sites-available/ken
- Paste the following content (replace
www.example.comwith your domain):
server {
listen 80;
server_name www.example.com;
root /var/www/ken;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
Step 2: Enable the Server Block
- Create a symbolic link to
sites-enabled:
sudo ln -s /etc/nginx/sites-available/ken /etc/nginx/sites-enabled/
Step 3: Test Nginx Configuration
- Run:
sudo nginx -t
- Ensure there are no errors.
Step 4: Reload Nginx
- Run:
sudo systemctl reload nginx
Step 5: Test Your Website
- Navigate to
http://www.example.comin your browser. - You should see your "Hello, I'm Ken" page.
Next Steps:
Enhance Your Website: Add more content or explore frameworks like React.
Continue Learning: Dive deeper into Linux, Nginx, and web development.
Share Your Success: Tell your friends about your new website.
Disclaimer: No Raspberry Pis were harmed in the making of this guide. Remember to keep your Pi cool and well-ventilated.
If you have any questions or run into any issues, feel free to ask. Happy Pi hosting!
SOCIAL SHARE CARD GENERATOR