Which environment variable to use on Heroku for services that only listen to https Which environment variable to use on Heroku for services that only listen to https heroku heroku

Which environment variable to use on Heroku for services that only listen to https


So I was able to resolve the issue after going through Heroku's documentation (extensively). Here are the key findings relating to this problem:

  1. Heroku uses a load balancer which proxies all its request.
  2. Heroku terminates any SSL communication from your app, so all requests are forwarded to your app over http; your clients' https requests are proxied over http.
  3. Since the requests are proxied, Heroku passes Forwarded headers for the originating request.
  4. Your app can only receive requests and should only listen to the PORT env variable.

Now that i have the in mind, I was able to configure my app correctly.

Listening on http not https: ASPNETCORE_URLS=http://*:$PORT

Using FowardedHeaders and Rewriter middlewares in AspNet core middleware pipeline:

var forwardedHeadersOptions = new ForwardedHeadersOptions {    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto};forwardedHeadersOptions.KnownNetworks.Clear();forwardedHeadersOptions.KnownProxies.Clear();app.UseForwardedHeaders(forwardedHeadersOptions);var rewriteOptions = new RewriteOptions ().AddRedirectToHttps(308);app.UseRewriter(rewriteOptions);...

The ForwardedHHeaders middleware maps the Forwarded headers to HttpContext.Request. And the Rewriter middleware will redirect http request scheme to https.