Nginx 通过两个文件从同一端口提供两项服务?

Nginx 通过两个文件从同一端口提供两项服务?

我有一个 nginx 服务器文件,它提供一些静态内容,看起来很简单,例如:

server {
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/this_host/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/this_host/privkey.pem;
    server_name static_content;

    # Proper rotation of session ticket encryption keys are not implemented, so
    # disable session tickets entirely
    ssl_session_tickets off;

    # Given that anticipated client devices are relatively modern, no need to
    # support insecure protocols
    ssl_protocols TLSv1.3;
    ssl_prefer_server_ciphers off;

    location /binaries/ {
        auth_basic "minimal protection";
        auth_basic_user_file /etc/nginx/auth/.htpasswd;
        root /var/www/static/;
    }

    location = /apple-app-site-association {
        alias /var/www/static/apple-app-site-association/apple-app-site-assocation;
        types { } default_type "content-type: application/json";
    }
}

我在生产服务器和临时服务器上重复使用它。在临时服务器上,我也想前置一个 API。如果我只是在以下位置添加另一个位置:

location ^~ /my_cool_api/v1/ {
    proxy_pass http://localhost:4000/my_cool_api/v1/;
}

但是,我为不同的服务使用了不同的服务器文件,而且当时它也被错误地命名为“static_content”。我想让它更加模块化,所以我尝试保留第一个文件,并将第二个文件添加到暂存服务器:

server {
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/this_host/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/this_host/privkey.pem;
    server_name my_cool_api;

    # Proper rotation of session ticket encryption keys are not implemented, so
    # disable session tickets entirely
    ssl_session_tickets off;

    # Given that anticipated client devices are relatively modern, no need to
    # support insecure protocols
    ssl_protocols TLSv1.3;
    ssl_prefer_server_ciphers off;

    location ^~ /accumulus_twig/v1/ {
        proxy_pass http://localhost:4000/accumulus_twig/v1/;
    }
}

但这不起作用。在 sites-enabled 中链接两者后,我只能让 API 工作,在这种情况下,error.log 显示它无法在 找到 (静态) 文件/usr/share/nginx/html/binaries/。有没有一种模块化的方法可以在 443 上定义一个带有所有正确证书等的服务器,但在不同的文件中定义不同的位置/匹配项?

答案1

读完这个问题的答案后(在 nginx 服务器块中使用“include”,但是保存在哪里?),我意识到我可以通过包含文件以模块化方式分解出我的位置:

server {
    listen              443 ssl;
    ssl_certificate     /etc/letsencrypt/live/this_host/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/this_host/privkey.pem;
    server_name https;

    # Proper rotation of session ticket encryption keys are not implemented, so
    # disable session tickets entirely
    ssl_session_tickets off;

    # Given that anticipated client devices are relatively modern, no need to
    # support insecure protocols
    ssl_protocols TLSv1.3;
    ssl_prefer_server_ciphers off;

    include /etc/nginx/includes/*.location;
}

然后可以为每个自文档文件添加一个不同的位置。

相关内容