Skip to content

Instantly share code, notes, and snippets.

@marcolussetti
Last active March 25, 2024 03:16
Show Gist options
  • Save marcolussetti/69995e16043ebbc2269402d2fb64f004 to your computer and use it in GitHub Desktop.
Save marcolussetti/69995e16043ebbc2269402d2fb64f004 to your computer and use it in GitHub Desktop.
Setup your own cors-anywhere proxy (Ubuntu, using Let's Encrypt)
#!/bin/bash
# Use sudo plz
# CONFIGURATION, EDIT PLEASE
ALLOWED_DOMAINS=https://localhost:5000
CORS_DOMAIN=cors.example.com
# Install dependencies
apt install npm
# Set up project
mkdir /opt
cd /opt
git clone https://github.com/Rob--W/cors-anywhere.git
cd /opt/cors-anywhere
npm install
# Make server.js runnable
echo '#!/usr/bin/env node' | cat - /opt/cors-anywhere/setup.js > temp && mv temp /opt/cors-anywhere/setup.js
chmod +x /opt/cors-anywhere/setup.js
# Set up service
cat <<EOT >> /etc/systemd/system/cors-anywhere.service
[Unit]
Description=CORS Anywhere Proxy
[Service]
ExecStart=/opt/cors-anywhere/server.js
Restart=always
User=nobody
Group=nogroup
Environment=PATH=/usr/bin:/usr/local/bin
Environment=PORT=8080
Environment=CORSANYWHERE_WHITELIST=$ALLOWED_DOMAINS
WorkingDirectory=/opt/cors-anywhere
[Install]
WantedBy=multi-user.target
EOT
# Install Caddy
curl -o /usr/bin/caddy -s 'https://caddyserver.com/api/download?os=linux&arch=amd64'
chmod +x /usr/bin/caddy
groupadd --system caddy
useradd --system --gid caddy --create-home --home-dir /var/lib/caddy --shell /usr/sbin/nologin \
--comment "Caddy web server" caddy
# Create Caddy service
curl -o /etc/systemd/system/caddy.service -s 'https://raw.githubusercontent.com/caddyserver/dist/master/init/caddy.service'
# Create Caddy configuration
mkdir /etc/caddy
cat <<EOT >> /etc/caddy/Caddyfile
$CORS_DOMAIN:443 {
reverse_proxy 127.0.0.1:8080
}
$CORS_DOMAIN:80 {
reverse_proxy 127.0.0.1:8080
}
EOT
# Start Caddy
systemctl enable caddy
systemctl start caddy
# Forward from port 80 so you can run it as unprivileged user
# This is only necessary if you want to avoid caddy, but then you don't get HTTPS
#iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
@marcolussetti
Copy link
Author

This lets you create a simple cors-anywhere proxy (with whitelist) on port 80, managed by systemd.

@PeWe79
Copy link

PeWe79 commented Jan 16, 2024

Hi, try to use this script but dosn't work. Thanks.

@marcolussetti
Copy link
Author

@PeWe79: that seems plausible as it's been a few years since I tried it on a new system.
Any idea at what steps is stops working and what error message you're getting?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment