Skip to content

Instantly share code, notes, and snippets.

@svandragt
Last active March 13, 2024 16:56
Show Gist options
  • Save svandragt/cbcb60b1cf0fea099adb54dddea491c7 to your computer and use it in GitHub Desktop.
Save svandragt/cbcb60b1cf0fea099adb54dddea491c7 to your computer and use it in GitHub Desktop.
WordPress reverse proxy
#!/usr/bin/env bash
# Requirements
if ! command -v docker &> /dev/null; then
echo 'Please install docker: https://docs.docker.com/engine/install/'
exit 1
fi
if ! command -v ngrok &> /dev/null; then
echo 'Please install ngrok: https://ngrok.com/download'
exit 1
fi
if [ -z "$1" ]; then
echo "Usage: wp-proxy.sh <example.altis.dev>"
exit 1 # Exit with a non-zero status code to indicate an error.
fi
WP_HOST="$1"
PATTERNED_WP_HOST=${WP_HOST//\./%.}
PATTERNED_PARENT=$(echo "$PATTERNED_WP_HOST" | cut -d'.' -f2-)
# Create OpenResty configuration
TMP_PROXY_DIR=/tmp/wp-proxy/conf.d
mkdir -p $TMP_PROXY_DIR
TMP_PROXY_FILE=$(mktemp)
tee "$TMP_PROXY_FILE" <<EOF
upstream backend {
server ${WP_HOST}:443 max_fails=5 fail_timeout=30;
}
server {
listen 8181;
server_name localhost;
location / {
more_clear_input_headers "Accept-Encoding";
more_clear_headers "Content-Security-Policy";
proxy_pass https://backend;
proxy_set_header Host ${WP_HOST};
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
proxy_set_header X-Proxied-By wp-proxy;
body_filter_by_lua_block {
ngx.arg[1] = ngx.arg[1]:gsub("https?://${PATTERNED_WP_HOST}/","/")
ngx.arg[1] = ngx.arg[1]:gsub("https?://${PATTERNED_PARENT}/","/")
}
}
}
EOF
cp "$TMP_PROXY_FILE" "$TMP_PROXY_DIR/wp-proxy.conf"
# Start the reverse proxy and ngrok
docker run -itd -v $TMP_PROXY_DIR:/etc/nginx/conf.d --network host --name wp-proxy-2023-09-08 openresty/openresty:bullseye-fat
ngrok http http://localhost:8181 --host-header=rewrite
docker rm -f wp-proxy-2023-09-08
@svandragt
Copy link
Author

svandragt commented Sep 8, 2023

Requirements:

  1. docker
  2. ngrok

Run:

chmod +x *.sh
./wp-proxy.sh my.wordpress.test

It downloads then runs openresty (nginx extended web server) and sets up a reverse proxy by loading a dynamically created configuration file so that the site can be accessed from other hostnames, and then ngrok to make it available to others.
this allows for example zero configuration testing on your iphone, impromptu demos etc.

Notes:

  1. it drops the browser content security policy to make loading any scripts work (tradeoff for temporary convenience), but requires no setup
  2. needs to have the local wordpress server running beforehand, as this sits in front of it
  3. It might work for any local webservice really, it's rewriting any absolute links to relative ones.

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