HTTPS proxy an API using Nginx

Updated: September 21, 2021

Need content for your business? Find top writers on WriterAccess!

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:

  1. Amazon S3 does HTTPS-SSL?! Oh … Amazon S3 does HTTPS-SSL?! Oh naw yu dedn’t! Why isn’t…
Share
facebook
linkedin
twitter
mail

Human Crafted Content

Find top content freelancers on WriterAccess.

Human Crafted Content

Find top content freelancers on WriterAccess.

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!

Talk to an expert and enhance your company’s marketing results.

Rock Content offers solutions for producing high-quality content, increasing organic traffic, building interactive experiences, and improving conversions that will transform the outcomes of your company or agency. Let’s talk.