如何使用 nginx 为多个 Web 服务器提供服务?

时间:2021-04-05 15:49:03

标签: nginx

我已经安装了 nginx,我想在同一台服务器上的同一用户下为两个不同的 Web 应用程序提供服务。

这是我已经使用的配置:

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    return 301 https://www.example.com$request_uri;
}

# HTTPS — proxy all requests to the Node app
server {
    # Enable HTTP/2
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name www.example.com;

    location ~* \.(?:ico|css|js|gif|jpe?g|png)$ {
      expires 30d;
      add_header Vary Accept-Encoding;
      access_log off;
    }
    root /home/myuser/main/dist;

    # Use the Let’s Encrypt certificates
    ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;

    # Include the SSL configuration from cipherli.st
    include snippets/ssl-params.conf;
}

如您所见,我在 /home/myuser 目录下有一个名为 main 的目录和一个 dist 目录。有使用 nginx 成功提供的静态文件。

我想在myuser目录下再添加一个目录,比如test。

所以我将使用 /myuser/test 并在那里为另一个 Web 应用程序提供服务。使用完全相同的 nginx 服务器。

我曾尝试在我上面提到的配置文件中编写许多变体,但它无法工作。

配置文件位于:/etc/nginx/sites-enabled/example.com.conf

我使用 sudo 编辑它。

1 个答案:

答案 0 :(得分:1)

如果您想从本地目录托管不同的静态文件,配置可能如下所示:

注意:如果使用 root 指令,您的位置 uri (/, /one) 将附加到根目录路径。

root 指令可用于每个位置块以设置文档根。 http://nginx.org/en/docs/http/ngx_http_core_module.html#root

这就是 alias 存在的原因。使用 alias 时,该位置不会成为目录路径的一部分。看一下这个: http://nginx.org/en/docs/http/ngx_http_core_module.html#alias

1.一个域 - 多位置

server {


  server_name example.com;
  listen 443 ssl;
  .....
  root /home/user/main/dist;
  location / {
     index index.html;
     # If you have some sort of React or Angular App you might want to use this
     # try_files $uri $uri/ /index.html;
     # If you just host a local files (css, js, html, png)...
     # try_files $uri $uri/ =404;
  }

  location /two {
     alias /home/main/example;
     index index.html;
     ..... 
  }


}

2.两个域 - 单一位置

server {


  server_name example.com;
  listen 443 ssl;
  .....
  root /home/user/main/dist;
  location / {
     index index.html;
     # If you have some sort of React or Angular App you might want to use this
     # try_files $uri $uri/ /index.html;
     # If you just host a local files (css, js, html, png)...
     # try_files $uri $uri/ =404;
  }

}

server {


  server_name example1.com;
  listen 443 ssl;
  .....
  root /home/user/main/test;
  location / {
     index index.html;
     # If you have some sort of React or Angular App you might want to use this
     # try_files $uri $uri/ /index.html;
     # If you just host a local files (css, js, html, png)...
     # try_files $uri $uri/ =404;
  }

}