微服务子文件夹架构的 NGINX 配置文件

NGINX Config File for Microservice Subfolder Architecture

请耐心等待,因为我没有太多配置 Nginx 的经验。

我想创建 micro-services 作为子文件夹。例如:www.example.com/users

USERS 是 micro-service,因此 USERS 也将是子文件夹的名称。

网站可以托管在 /var/www/html/ 或 /var/www/html/example。com/public_html(假设这个问题是这个)

所以在主文件夹里面,/var/www/html/example.com/public_html里面有很多文件夹,每个文件夹代表一个micro-service.

/var/www/html/example.com/public_html/users/
/var/www/html/example.com/public_html/students/
/var/www/html/example.com/public_html/teachers/
/var/www/html/example.com/public_html/parents/

每个 micro-service 都会有一个最新的文件夹,其中包含要执行的代码。

/var/www/html/example.com/public_html/users/latest/

每个最新的文件夹都有 2 个文件夹 - 包含 SPA 前端代码的 APP 和包含 API 代码的 API

/var/www/html/example.com/public_html/users/latest/app/
/var/www/html/example.com/public_html/users/latest/api/

我想根据需要添加和删除文件夹,而不更改 Nginx 配置文件。 如果该文件夹存在,我希望显示相关的前端代码。否则 404

我知道我可以根据需要在 Nginx 位置添加文件夹,但这不是我想要的。

(不想执行以下代码)

location /users {
  alias /var/www/html/example.com/public_html/users/latest/app
}

location /api/users {
  alias /var/www/html/example.com/public_html/users/latest/api
}

我正在尝试确定是否可以根据 url.

配置 NGINX 以指向相关文件夹

这是我目前所拥有的,但对于我正在尝试的所有内容,它都显示为 404。我正在努力在 Go-lang 中编写 API 但由于我有使用 PHP 的经验,所以我在切换到 Go 之前先走那条路。

server {

    listen 80;
    listen [::]:80;
    server_name _;

    root /var/www/html/example.com/public_html;
    index index.html;

    location ^/<service>/<additional-optional-parameters-can-go-here>$ {
      root /var/www/html/example.com/public_html/<service>/latest/app;
      try_files $uri $uri/ =404
    }

    location ^/api/<service>/<additional-optional-parameters-can-go-here>$ {
      root /var/www/html/example.com/public_html/<service>/latest/api;
      try_files $uri $uri/ =404

      location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_param SCRIPT_FILENAME $request_filename;
            fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        }

    }

    location ~ /\.ht {
        deny all;
    }

}

我认为您可以在位置和服务器行中使用正则表达式。

也许这会有所帮助

server_name ~^(?<subdomain>.+)\.domain\.tdl$ ~^(?<subdomain>.+)\.domain2\.tdl$ domain.tdl domain2.tdl;

location ~ ^/sitename/[0-9a-z]+/index.php$ {
    fastcgi_pass phpcgi;
}

location ~ \.php$ {
    return 404;
}

location ~ ^/a/b/(?<myvar>[a-zA-Z]+) {
   # use variable $myvar here
   if ($myvar = "sth") { ... }
}

# Example using the subdomain var created in last steps
sub_filter_once off;
sub_filter 'Site Text' '$subdomain';
sub_filter 'Site Text' '$myvar';

我个人喜欢为每个服务创建不同的 conf 文件,然后发出 "service nginx reload"。也许您还可以自动生成 conf 文件。

以防其他人正在尝试类似的方法。 我继续 Freelancer.com 并雇了一个人来帮助我。

location ~ ^/api/([a-z]+)/.*?$ {
    alias $folder_path//$api_path;
    rewrite ^/api/([a-z]+)/.*?$ //$api_path last;
}

location ~ ^/([a-z]+)/(?:(?!\blatest\b).)*$ {
    alias $folder_path//$app_path;
    rewrite ^/([a-z]+)/(?:(?!\blatest\b).)*$ //$app_path last;
}