Mastodon

Force https in Angular Application Deployed on Pivotal CloudFoundry

This will be a short one.

I am working on an Angular 6 application that is deployed on a Pivotal Cloud Foundry, using the nginx-buildpack. With the default nginx.conf, http and https requests are served. The https request is secured using the certificate for *cfapps.io, which is nice to have without any configuration.

However, allowing http requests opens the door for accidental unencrypted logins, which I want to avoid. Hence, I want to forward all http-requests to https.

Here’s the working nginx.conf for this:

worker_processes 1;
daemon off;
 
error_log stderr;
events { worker_connections 1024; }
 
http {
  charset utf-8;
  log_format cloudfoundry 'NginxLog "$request" $status $body_bytes_sent';
  access_log /dev/stdout cloudfoundry;
  default_type application/octet-stream;
  include mime.types;
  sendfile on;
 
  tcp_nopush on;
  keepalive_timeout 30;
  port_in_redirect off; # Ensure that redirects don't include the internal container PORT - 8080
 
  server {
 
    # Listen to the port defined in environment variable
    listen ;
 
    # directory where static Angular files are in
    root public;
 
    # Configure nginx to forward URLs like mydomain.com/topic1/detail to index.html so that request can be handled by Angular instead of nginx trying to find an topic1/detail.html.
    try_files $uri $uri/ /index.html;
 
    # Forward every request to https
    if ($http_x_forwarded_proto != "https") {
      return      301         https://$host$request_uri;
    }
  }
}

This is the complete configuration file. Only the last part is important for the redirect. However, the rest may serve as reference for future-me. You’re welcome, Steven! ;)