带子域名支持的Nginx api网关仓库

带子域名支持的Nginx api网关仓库

我正在按照教程设置 API 代理,我在同一个 VPS 上运行生产和开发服务器应用程序

https://www.nginx.com/blog/deploying-nginx-plus-as-an-api-gateway-part-1/

live.domain.com我在两个平台上都通过 certbot 使用 SSL 管理我的域名dev.domain.com

我被困在“定义仓库 API”问题在于,解释的路由是基于 URL 路径位置,它没有解释如何处理在其上设置的子域。

我已经设置:api_gateway

include api_backends.conf;
include api_keys.conf;

server {
    access_log /var/log/nginx/api_live.log main; # Each API may also log to a 
                                                   # separate file

    listen 443 ssl;
    server_name live.domain.com;

    # TLS config
    ssl_certificate      /etc/letsencrypt/live/live.domain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key  /etc/letsencrypt/live/live.domain.com/privkey.pem; # managed by Certbot
    include              /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam          /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    ssl_session_cache    shared:SSL:10m;
    ssl_session_timeout  5m;
    ssl_ciphers          HIGH:!aNULL:!MD5;
    ssl_protocols        TLSv1.2 TLSv1.3;

    # API definitions, one per file
    include api_conf.d/*.conf;

    # Error responses
    error_page 404 = @400;         # Treat invalid paths as bad requests
    proxy_intercept_errors on;     # Do not send backend errors to client
    include api_json_errors.conf;  # API client-friendly JSON errors
    default_type application/json; # If no content-type, assume JSON
}
# *repeated for dev.domain.com*

api_后端

upstream live {
zone live_service 64k;
server 127.0.0.1:4000
}
upstream dev {
zone dev_service 64k;
server 127.0.0.1:2000
}

无论如何我都可以通过以下方式来处理它:

location / {
    # Policy configuration here (authentication, rate limiting, logging...)
    #
    access_log /var/log/nginx/warehouse_api.log main;

    # URI routing
    #
# if subdomain live
    location / {
        proxy_pass http://live;
    }
# else if subdomain dev
    location / {
        proxy_pass http://dev;
    }

    return 404; # Catch-all
}

也许我可以使用我找到的这个片段。

    if ($host = live.domain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

这可能吗?

    if ($host = live.domain.com){
        location /api {
                proxy_pass http://live/api;
        }
# AND/OR
        location /docs/ {
                proxy_pass https://live$request_uri
        }
    }

答案1

您的配置中一切几乎都很好,只是您用那些包含和location / {}块欺骗了自己,而没有包括第二个 vhost 配置部分。

你只需要把live.domain.comdev.domain.com location / {}相应server {}块中的块,仅此而已(一个包含proxy_pass http://live;在活动块中,依此类推)。

if () {}此时不要使用块,你不需要它。

是的,您有点缺少非 TLSserver {}块,但我想这是另一个问题。

相关内容