Have you ever been faced with using a JSONP API for your favourite service, only to have your HTTPS site throw complaints that all elements of the page weren’t delivered securely? Since the calls are being made client-side, unless you get lucky and the service has an HTTPS version of their API, you’ll have to resort to using a proxy. Luckily, nginx makes it really easy to configure your own.
I recently ran into this problem when I was using the Chartbeat API. We already used nginx for a lot of our reverse-proxying, so it just took a config change to get it proxying the Chartbeat API as well. I’ve included the configuration below. In the client-side Javascript, we then just changed any call like https://api.chartbeat.com/toppages/?host=[host]&limit=[limit]&apikey=[apikey] to be https://www.EXAMPLE.com/api.chartbeat.com/toppages/?host=[host]&limit=[limit]&apikey=[apikey]. For Chartbeat, the request looks just like it would if it were coming from the client directly.
Once you have the basic functionality in-place, you can even add some security by hiding the apikey parameter from public-view, or add some scaling by putting a CDN in-front of your domain. Is there anything nginx can’t do?
server { listen 443; ssl on; ssl_certificate /root/my_certificate.pem; ssl_certificate_key /root/my_certificate.key; server_name _; server_name_in_redirect off; location /api.chartbeat.com/ { rewrite /api.chartbeat.com(/.*)$ $1 break; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass https://api.chartbeat.com; proxy_set_header Host api.chartbeat.com; proxy_connect_timeout 1; proxy_next_upstream error timeout http_500 http_502 http_503 http_504 http_404; proxy_intercept_errors on; expires 30; add_header Content-Type text/javascript; break; } }
Related posts:
- Amazon S3 does HTTPS-SSL?! Oh … Amazon S3 does HTTPS-SSL?! Oh naw yu dedn’t! Why isn’t…