Force https in Angular application deployed on Pivotal Cloud Foundry


Posted by Steven

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:

  1. worker_processes 1;
  2. daemon off;
  3.  
  4. error_log stderr;
  5. events { worker_connections 1024; }
  6.  
  7. http {
  8. charset utf-8;
  9. log_format cloudfoundry 'NginxLog "$request" $status $body_bytes_sent';
  10. access_log /dev/stdout cloudfoundry;
  11. default_type application/octet-stream;
  12. include mime.types;
  13. sendfile on;
  14.  
  15. tcp_nopush on;
  16. keepalive_timeout 30;
  17. port_in_redirect off; # Ensure that redirects don't include the internal container PORT - 8080
  18.  
  19. server {
  20.  
  21. # Listen to the port defined in environment variable
  22. listen {{port}};
  23.  
  24. # directory where static Angular files are in
  25. root public;
  26.  
  27. # 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.
  28. try_files $uri $uri/ /index.html;
  29.  
  30. # Forward every request to https
  31. if ($http_x_forwarded_proto != "https") {
  32. return 301 https://$host$request_uri;
  33. }
  34. }
  35. }

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! ;)

Category: 
Share: