You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu22.04下配置Express.js与sites-available.conf实现3000端口HTTPS访问

解决HTTPS证书未关联443端口导致接口无法正常访问的问题

方案一:让Express直接监听443端口(适用于仅托管Express服务的场景)

  • 修改Express代码中的监听端口为443:
    var privateKey  = fs.readFileSync('/etc/ssl/private/apache-selfsigned.key', 'utf8');
    var certificate = fs.readFileSync('/etc/ssl/certs/apache-selfsigned.crt', 'utf8');
    
    var credentials = {key: privateKey, cert: certificate};
    var httpsServer = https.createServer(credentials, app);
    // 将监听端口改为443
    httpsServer.listen(443,function (err) {
            if (err) console.log(err);
            console.log("Server listening on PORT 443");
        });
    
  • 停止占用443端口的Apache服务:
    sudo systemctl stop apache2
    
  • 重启Express服务,访问 https://amaurypichat.fr/getdata(无需添加3000端口)

方案二:使用Apache反向代理(推荐,可同时托管静态文件与Express服务)

  • 启用Apache反向代理相关模块:
    sudo a2enmod proxy proxy_http proxy_ssl
    
  • 修改Apache的/etc/apache2/sites-available.conf配置文件,在443虚拟主机中添加反向代理规则:
    <VirtualHost *:443>
       DocumentRoot /var/www/html/prod
    
       SSLEngine on
       SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
       SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
    
       # 反向代理指向本地3000端口的Express服务
       ProxyPass /getdata http://localhost:3000/getdata
       ProxyPassReverse /getdata http://localhost:3000/getdata
    </VirtualHost>
    <VirtualHost *:80>
           ServerName amaurypichat.fr
           Redirect / https://amaurypichat.fr/
    RewriteEngine on
    RewriteCond %{SERVER_NAME} =amaurypichat.fr
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
    </VirtualHost>
    
  • 简化Express配置(本地通信无需HTTPS,改为HTTP服务):
    // 改用HTTP服务器
    var httpServer = http.createServer(app);
    httpServer.listen(3000,function (err) {
            if (err) console.log(err);
            console.log("Server listening on PORT 3000");
        });
    
  • 重启Apache与Express服务:
    sudo systemctl restart apache2
    
  • 访问 https://amaurypichat.fr/getdata 即可正常访问接口

内容的提问来源于stack exchange,提问作者aa bb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 02:47:38