PlexConnect on Synology with WebStation

I’m using Plex to manage my totally legal home movies. It turns out you can use PlexConnect to link Plex with your Apple TV.

I want to run PlexConnect on my Synology NAS, but it requires access to port 80 and 443. I already have WebStation serving websites on those ports, so there’s a conflict. Oh noes!

The problem

By default, PlexConnect runs a web server on port 81 and 444, with an nginx reverse proxy set to serve on port 80 and 443. Unfortunately, the reverse proxy isn’t going to work if Synology WebStation is already serving on 80/443.

The fix

Using the magic of iptables it’s possible to redirect TCP requests from a certain source on a specific interface to redirect to a different local port using command:

iptables -t nat -A PREROUTING -s [source ip] -p tcp --dport [request port] -j REDIRECT --to-port [destination port]

For example, my Apple TV has a static IP of 192.168.1.161. Upon connecting to the Diskstation via SSH:

$ sudo su
# iptables -t nat -A PREROUTING -s 192.168.1.161  -p tcp --dport 443 -j REDIRECT --to-port 444
# iptables -t nat -A PREROUTING -s 192.168.1.161  -p tcp --dport 80 -j REDIRECT --to-port 81

So now, any requests from 192.168.1.161 on port 80 and 443 will be redirected locally to port 81 and 444, the PlexConnect ports.

Making it permanent

Unfortuantely, the iptables command isn’t permanent–it will reset after a server restart. The /var/packages/plexconnect/scripts/start-stop-status script controls the commands when the PlexConnect package starts.

Line 17 defines the start_daemon () subroutine. You can add your iptables declarations to the function to automatically insert them every time the PlexConnect daemon starts. My start-stop-status start_daemon () accounts for two Apple TVs:

start_daemon ()
{
    su -c "iptables -t nat -A PREROUTING -s 192.168.1.161  -p tcp --dport 80 -j REDIRECT --to-port 81"
    su -c "iptables -t nat -A PREROUTING -s 192.168.1.162  -p tcp --dport 80 -j REDIRECT --to-port 81"
    su -c "iptables -t nat -A PREROUTING -s 192.168.1.161  -p tcp --dport 443 -j REDIRECT --to-port 444"
    su -c "iptables -t nat -A PREROUTING -s 192.168.1.162  -p tcp --dport 443 -j REDIRECT --to-port 444"

    su -c "${PYTHON} ${PROG_PY} --pidfile ${PID_FILE}"
}

Remember to assign your Apple TVs a static IP, either on the Apple TV itself or via your DHCP server, otherwise you will be constantly updating your iptables declarations with the correct IP.