如何在同一台服务器上运行node和apache以允许用户通过https访问API?

5t7ly7z5  于 2023-10-23  发布在  Apache
关注(0)|答案(1)|浏览(119)

我在同一台服务器上运行Node和Apache,其中Node是后端服务器,Axios请求从前端收集用户数据。
我使用Apache通过certbot请求SSL证书并成功。我试图部署节点后端访问我的endpoint(website.com/endpoint)
我能够看到测试index.html,位于网站文件夹.当我尝试aws.website.com/endpoint时,我得到服务器超时和404未找到错误。
我的应用程序在Linux服务器中的位置是var/www/website.com,而不是默认的var/www/html路径。
我的问题是:如何在同一台服务器上运行node和apache,以允许用户通过https访问应用程序?

  • 更新:你需要节点应用程序在一个单独的端口上运行,在我的情况下是3001,Apache在一个单独的端口上运行,即80,并通过mod-proxy使用反向代理。

下面是000-default.conf文件:

<VirtualHost *:80>
    ProxyPreserveHost On
    ProxyPass / http://18.191.235.31/
    ProxyPassReverse / http://18.191.235.31/
        ServerName aws.website.com
        ServerAdmin example@localhost
        DocumentRoot /var/www/aws.backend-dg.com
</VirtualHost>

下面是我的Apache虚拟主机的config文件:website/com.conf

<VirtualHost *:80>
    ServerName aws.website.com
    ...
    DocumentRoot /var/www/aws.website.com
    ...
RewriteEngine on
RewriteCond %{SERVER_NAME} =aws.website.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

这是我的'website.com.le-ssl.conf'(由certbot手动生成)`

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName aws.website.com
    ....
    DocumentRoot /var/www/aws.website.com
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

SSLCertificateFile /etc/letsencrypt/live/website/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/website/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

我的default-ssl.conf

<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
            DocumentRoot /var/www/aws.backend-dg.com
            ....
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
            ....
            SSLEngine on
            ....
            SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
            SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
            ....
        </VirtualHost>
</IfModule>

App.js文件

const cors = require("cors");
const mongoose = require("mongoose");
const express = require("express");
const logger = require("morgan");
const app = express();
require("./models/Email");
const routes = require("./routes/routes");

app.use(cors());
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "DELETE, PUT, GET, POST");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Express only serves static assets in production
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
}
app.get('*',(req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
app.use(express.json());
app.use(logger("dev"));
app.use("/", routes);
app.use("/search", express.static("search"));

const mongoURI =
  "mongodb+srv://somename@cluster................";

const conn = mongoose.createConnection(mongoURI);

mongoose.connect(
  mongoURI,
  { useNewUrlParser: true },
  { useUnifiedTopology: true }
);

conn.once("open", () => {
  console.log("Connection Successful");
});

conn.on("error", console.error.bind(console, "MongoDB connection error:"));

 const server = app.listen(3001, () => {
 console.log(`Express running PORT ${server.address().port}`);
 });

const express = require("express");
const router = express.Router();
const emailController = require('../controllers/EmailController');

router.get('/', emailController.baseRoute);
router.post('back/get-email', emailController.createEmail);

module.exports = router;
epggiuax

epggiuax1#

答案是保护节点后端服务器,以便用户留在安全的HTTPS地址上。您可以通过将SSL密钥分配给节点服务器来实现这一点。然后编辑app.js文件以连接到HTTPS,而不是HTTP。上面的app.js只连接到HTTP。所以这个问题需要解决。最后,编辑Apache虚拟主机中的反向代理,将HTTP转发到HTTPS
在我的情况下,前端是安全的,通过HTTPSSSL证书从让我们加密(certbot)即https://website.com,但后端是不安全的,所以当我试图去https://websote/endpoint有一个错误。这是因为后端app.js文件在需要连接到HTTPS时连接到HTTP服务器。

注意:如果您有一个安全的网站/应用程序,并且您向不安全的HTTP地址发出Axios请求,则会收到cors错误,说明您需要将HTTP更改为HTTPS。您可以通过使node.js服务器安全来实现这一点。

细分如下:

1a.在节点文件夹中创建一个单独的目录来存放证书。sudo mkdir directory_name
1b. * 将SSL证书从Apache服务器复制到Node服务器目录。

sudo cp etc/letsencrypt/live/your_webiste_folder/privkey.pem /var/www/directory_name
sudo cp /etc/letsencrypt/live/your_website_folder/fullchain.pem /var/www/directory_name
click here for guide about copying files and its contents

1c为该文件夹分配权限规则。我使用ubuntu作为我的组,因为root拥有目录和密钥的所有权。

click this link to create a group and learn about permissions

-步骤a。更改拥有密钥文件的组的所有权

  • 注意:您需要使用root执行此操作,请键入以下cmdsudo -i
    chown group_name /var/path_to_webiste/cert_directory
    步骤B**。更改组中密钥的所有权
    chown group_name /var/path_to_website/privkey.pem
    chown group_name /var/path_to_website/fullchain.pem

1d检查权限是否成功应用ls -l

  • 下面第3行是一个例子的权限的目录根
  • 下面第4行是一个例子的权限目录group_name(ubuntu).你想在你的代码中看到这一行。
root@ip-123-45-67-890:/var/www# ls -l
total 8
drwxr-xr-x 6 root   root   4096 Oct 20 23:50 directory_name
drwxr-xr-x 2 ubuntu ubuntu 4096 Oct 20 16:10 directory_name

Click here to learn more

  • 2.编辑app.jsserver.js连接到HTTPS服务器,而不是HTTP *
    注意:当您在app.jsserver.js中提供Node文件夹中SSL证书目录的位置路径时,Node将无法看到,这就是您需要分配权限的原因。

App.js:

//imports
   ......
    
    //use node over secure server
    const https = require("https"),
        fs = require("fs");
    
    const sslServer =  https.createServer (
    {
      key: fs.readFileSync('/var/path_to_privkey.pem'),
      cert: fs.readFileSync('/var/path_to_fullchain.pem'),
    },
    app  <---MAKE SURE TO PASS APP IN
    )
    
   ......
   ......
   
sslServer.listen(3000, () => {
  console.log(`Express running PORT 3000 working!`)
});

Click here for a walkthrough process for above app.js code
1.通过ufw命令指定防火墙权限规则,以允许您从app.js文件(即3001)中使用的port

  • 注意:如果你尝试连接到port,你得到一个超时,然后你的Apache防火墙设置不允许端口来通过,这就是为什么你需要编辑Apache防火墙权限sudo ufw allow 3001
    1.编辑000-default.confwebsite.com.confwebsite.com-le-ssl文件以从HTTP转发到HTTPS。- 注意:website.com.conf-le-sslcertbotletsencrypt生成
    000-default.conf:
<VirtualHost *:80>
        ServerName website.com
        ServerAlias www.website.com
        DocumentRoot /var/www/website.com

        ProxyPreserveHost On
        ProxyRequests Off
        ProxyPass /get-email https://1.234.567.890:3001/
        ProxyPassReverse /get-email https://1.234.567.890:3001/

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

website.com.conf:

<VirtualHost *:80>
    ServerName website.com
    ServerAlias www.website.com
    DocumentRoot /var/www/aws.backend-dg.com

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    ProxyPreserveHost Off
    ProxyRequests Off
    ProxyPass / http://1.234.567.890:3001/
    ProxyPassReverse / https://1.234.567.890:3001/

    RewriteEngine on
    RewriteCond %{SERVER_NAME} =aws.backend-dg.com [OR]
    RewriteCond %{SERVER_NAME} =3.144.239.224:3001 [OR]
    RewriteCond %{SERVER_NAME} =aws.backend-dg.com:3001 [OR]
    RewriteCond %{SERVER_NAME} =www.aws.backend-dg.com
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

website.com-le-ssl.conf:

<IfModule mod_ssl.c>
<VirtualHost *:443>
  ServerName website.com
  ServerAlias www.website.com
  DocumentRoot /var/www/website.com

  SSLProxyEngine On
  ProxyPass /get-email http://1.234.567.890:3001/
  ProxyPassReverse /get-email https://1.234.567.890:3001/
  ProxyPreserveHost Off
  ProxyRequests Off

  SSLEngine On
  SSLCertificateFile /etc/letsencrypt/live/website.com/fullchain.pem
  SSLCertificateKeyFile /etc/letsencrypt/live/website.com/privkey.pem
</VirtualHost>
</IfModule>

相关问题