HTTPS proxy an API using Nginx

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[host]&limit=[limit]&apikey=[apikey] to be[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?

  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 /
    rewrite /*)$ $1 break;
    proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host;
    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;


Related posts:

  1. Amazon S3 does HTTPS-SSL?! Oh … Amazon S3 does HTTPS-SSL?! Oh naw yu dedn’t! Why isn’t…

Subscribe to our blog

Sign up to receive Rock Content blog posts

Rock Content WriterAccess - Start a Free Trial

Order badass content with WriterAccess. Just as we do.

Find +15,000 skilled freelance writers, editors, content strategists, translators, designers and more for hire.

Want to receive more brilliant content like this for free?

Sign up to receive our content by email and be a member of the Rock Content Community!