Home > Software engineering >  Nodejs: How to reverse proxy TLS certificates with Caddy (Cloudflare)?
Nodejs: How to reverse proxy TLS certificates with Caddy (Cloudflare)?

Time:12-05

this is my first time deploying nodejs from localhost to the live server. I am using aapanel for my live server.

Here is the relevant code in node server.js file:

const hostname = 'localhost';
// const hostname = 'www.thespacebar.io';

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, hostname, () => {
    console.log(`Server is running on port ${PORT}.`);
});

Here is my pm2 settings: enter image description here

I am unable to open my nodejs app with GET https://www.thespacebar.io:8080, but it works for GET http://www.thespacebar.io:8080

GET https://www.thespacebar.io:8080 does not work with error:

This site can’t provide a secure connection
ERR_SSL_PROTOCOL_ERROR

Anyone know what I did wrong?

EDIT: I have installed Caddy and setup the Caddyfile in /etc/caddy like this:

# The Caddyfile is an easy way to configure your Caddy web server.
#
# Unless the file starts with a global options block, the first
# uncommented line is always the address of your site.
#
# To use your own domain name (with automatic HTTPS), first make
# sure your domain's A/AAAA DNS records are properly pointed to
# this machine's public IP, then replace ":80" below with your
# domain name.

import ./thespacebar.io

:80 {
        # Set this path to your site's directory.
        root * /usr/share/caddy

        # Enable the static file server.
        file_server

        # Another common task is to set up a reverse proxy:
        # reverse_proxy localhost:8080

        # Or serve a PHP site through php-fpm:
        # php_fastcgi localhost:9000
}

# Refer to the Caddy docs for more information:
# https://caddyserver.com/docs/caddyfile

and created the adjacent file thespacebar.io:

thespacebar.io {
  reverse_proxy localhost:8080
}

but when I visit https://thespacebar.io/, I end up at index.html instead of the JSON { message: "Welcome to bezkoder application." } and POST http://www.thespacebar.io/api/verification/callback with body param verify_token:abcde is supposed to show the JSON:

{
    "message": "Callback called successfully."
}

instead of 404 Not Found

EDIT 2: I have removed the portion:

# :80 {
        # Set this path to your site's directory.
#       root * /usr/share/caddy

        # Enable the static file server.
#       file_server

        # Another common task is to set up a reverse proxy:
        # reverse_proxy localhost:8080

        # Or serve a PHP site through php-fpm:
        # php_fastcgi localhost:9000
# }

# Refer to the Caddy docs for more information:
# https://caddyserver.com/docs/caddyfile

from etc/caddy/Caddyfile

but when I run caddy run Caddyfile and caddy reload Caddyfile, I am getting this error:

[root@vultrguest caddy]# caddy run Caddyfile
2022/12/02 08:11:44.132 INFO    using adjacent Caddyfile
2022/12/02 08:11:44.132 WARN    Caddyfile input is not formatted; run the 'caddy fmt' command to fix inconsistencies    {"adapter": "caddyfile", "file": "Caddyfile", "line": 12}
2022/12/02 08:11:44.133 INFO    admin   admin endpoint started  {"address": "localhost:2019", "enforce_origin": false, "origins": ["//localhost:2019", "//[::1]:2019", "//127.0.0.1:2019"]}
2022/12/02 08:11:44.133 INFO    http    server is listening only on the HTTPS port but has no TLS connection policies; adding one to enable TLS {"server_name": "srv0", "https_port": 443}
2022/12/02 08:11:44.133 INFO    http    enabling automatic HTTP->HTTPS redirects        {"server_name": "srv0"}
2022/12/02 08:11:44.133 INFO    tls.cache.maintenance   started background certificate maintenance      {"cache": "0xc000151030"}
2022/12/02 08:11:44.133 INFO    tls.cache.maintenance   stopped background certificate maintenance      {"cache": "0xc000151030"}
Error: loading initial config: loading new config: http app module: start: listening on :80: listen tcp :80: bind: address already in use
[root@vultrguest caddy]# caddy reload Caddyfile
2022/12/02 08:11:49.875 INFO    using adjacent Caddyfile
2022/12/02 08:11:49.876 WARN    Caddyfile input is not formatted; run the 'caddy fmt' command to fix inconsistencies    {"adapter": "caddyfile", "file": "Caddyfile", "line": 12}
Error: sending configuration to instance: performing request: Post "http://localhost:2019/load": dial tcp [::1]:2019: connect: connection refused
[root@vultrguest caddy]# 

If I run GET http://www.thespacebar.io:8080 I get:

Web server is down Error code 521
Visit cloudflare.com for more information.
2022-12-02 08:22:13 UTC
You

EDIT3: The site I am trying to setup reverse proxy is using cloudflare, so I have modified my Caddyfile to:

# The Caddyfile is an easy way to configure your Caddy web server.
#
# Unless the file starts with a global options block, the first
# uncommented line is always the address of your site.
#
# To use your own domain name (with automatic HTTPS), first make
# sure your domain's A/AAAA DNS records are properly pointed to
# this machine's public IP, then replace ":80" below with your
# domain name.

# import ./thespacebar.io

# cloudflare 
(cf) {
    tls {
        resolvers 1.1.1.1
        dns cloudflare [cf-token-goes-here]
    }
}

but when I run `caddy run Caddyfile`, I got this error:
`Error: adapting config using caddyfile: parsing caddyfile tokens for 'tls': Caddyfile:17 - Error during parsing: getting module named 'dns.providers.cloudflare': module not registered: dns.providers.cloudflare`

thespacebar.io {
  import cf
  reverse_proxy localhost:8080
}

but when I goto cd /etc/caddy and caddy run Caddyfile I get the error:

Error: adapting config using caddyfile: parsing caddyfile tokens for 'tls': Caddyfile:17 - Error during parsing: getting module named 'dns.providers.cloudflare': module not registered: dns.providers.cloudflare

all the tutorials for adding this module (dns.providers.cloudflare) are for xcaddy and not caddy, how do I add this module for caddy?

CodePudding user response:

Caddy is simple to setup as a reverse proxy, and it gets letsencrypt SSL certs for you with minimal fuss

{
    email [email protected]
}
thespacebar.io {
     reverse_proxy localhost:8080
}

I see you've posted an update - the one thing I would remove is

:80 {
  .....
}

If you read the text you posted it does say to replace :80 with your domain (but don't add :80 or caddy won't do the certificate for the domain)

I also see you haven't set up a global section with an email address - I'm fairly sure that needs to be there (don't quote me on that) for letsencrypt to work - at least it used to when I first started using caddy

CodePudding user response:

here is some pseudo code for a generic caddyfile for caddy v2
for the code below replace "\*" with "*" "\" is used below to escape "/*" in the markdown

this code will add basic security headers and cors to the response
it will proxy pass thru to a process on localhost port 9883
if you have a dns record for your server it will set up the letsencrypt certs for you and renew them when required
see caddy snippets https://caddyserver.com/docs/caddyfile/concepts#snippets

# begin common code block snippet to be imported into the server block, 
# for example here we set common security headers
# see the markdown escape comment above for "/\*" should be "/*"
(common) {
    header /\* {
        -Server
        -X-Powered-By
         X-Permitted-Cross-Domain-Policies none
         X-Frame-Options DENY
         X-Content-Type-Options nosniff
         Strict-Transport-Security "max-age=63072000 includeSubDomains preload"
         Referrer-Policy no-referrer
        }
}
# cors snippet
(cors) { 
    @cors_preflight method OPTIONS
# "{args.0}" is an input value used when calling the snippet
  
    @cors header Origin "{args.0}"  
        handle @cors_preflight {
            header Access-Control-Allow-Origin  "{args.0}"
            header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE"
            header Access-Control-Allow-Headers "Content-Type"
            header Access-Control-Max-Age "3600"
            respond "" 204
    }
}

# main server block
# dns record for server is myserver.edu
myserver.edu { 

# import common sec headers snippet
    import common   
# import cors snippet passing server name parameter, wildcard cors poor sec
    import cors myserver.edu  

# proxy redirect see handle_path directive 
# https://caddyserver.com/docs/caddyfile/directives/handle_path
# see the markdown escape comment above for "/\*" should be "/*"
    handle_path /somepath/\* {
        reverse_proxy localhost:9883 {
            header_up X-Real-IP {remote_host}
            # caddy will add X-Forwarded-For for you so not need this one
            #header_up X-Forwarded-For {remote_host}
            header_down Content-Security-Policy "media-src blob:"
            }
        }

}

  • Related