There are lots of solutions. Your script would work, but if SSH is not accessible but http is you should fix the underlying cause rather then the hack of rebooting. (Wild guess, too mich swap on spinning disk. Try set vm.swappiness to 5 and reduce - but dont eliminate - the swap partition size if its Linux and hats the cause).
As others have said "proper" servers usually have out-of-band management which allows for remote reboots and a lot more (iLo for HP and iDrac for Dell for example).
Another option is to get a power switch with the ability to toggle power ports. They are not that expensive.
Going "more hack", look at Watchdog timer support - there are lots if variants and options here depending in hardware and OS, but the idea is the system monitors itself and if the OS does not write to a special device periodically the system reboots.
If you are a hacker (in the ethical sense), or know someone who is, you should be able to use a Raspberry pi (or even an arduino if you make your own watchdog or have WIFI) using the basic computer to drive a relay (As it happens I was looking at an arduino board with relay for under US$10 earlier today - On aliexpress do a search for esp8266 relay)
Another solution - which worked well for me - was to convert my bare metal to a VM server ( lf budget is a concern look at KVM/proxmox) and ensured I did not overprovision resources and virtualise the app. I this way you can go into your hypervisor and debug and perform reboots in most cases. You can further improve things by breaking different functions onto different VM's so that in case of a failure you likely still have partial service - this, of course assumes you don:t just go the cloud/vm route.