diff --git a/optimade/server/routers/utils.py b/optimade/server/routers/utils.py index e79983547..704f61830 100644 --- a/optimade/server/routers/utils.py +++ b/optimade/server/routers/utils.py @@ -232,16 +232,19 @@ def get_base_url( Take the base URL from the config file, if it exists, otherwise use the request. """ + if CONFIG.base_url: + return CONFIG.base_url.rstrip("/") + parsed_url_request = ( urllib.parse.urlparse(parsed_url_request) if isinstance(parsed_url_request, str) else parsed_url_request ) - return ( - CONFIG.base_url.rstrip("/") - if CONFIG.base_url - else f"{parsed_url_request.scheme}://{parsed_url_request.netloc}" - ) + base_url = f"{parsed_url_request.scheme}://{parsed_url_request.netloc}" + if CONFIG.root_path: + base_url = base_url + CONFIG.root_path.rstrip("/") + + return base_url def get_entries( diff --git a/tests/server/routers/test_utils.py b/tests/server/routers/test_utils.py index 37b1f8ee5..fc88509d7 100644 --- a/tests/server/routers/test_utils.py +++ b/tests/server/routers/test_utils.py @@ -111,3 +111,38 @@ def test_get_providers_warning(caplog, top_dir): from optimade.server.data import providers assert providers == providers_cache + + +def test_get_base_url(): + """ + This tests whether the base_url is correctly extracted from the request. + """ + from optimade.server.config import CONFIG + from optimade.server.routers.utils import get_base_url + + base_url_org = CONFIG.base_url + root_path_org = CONFIG.root_path + CONFIG.base_url = None + CONFIG.root_path = "/optimade" + request_urls = ( + "http://www.example.com", + "http://www.example.com/", + "http://www.example.com/optimade/v1/links", + "http://www.structures.com/links", + "https://www.links.org/optimade/structures/123456", + ) + base_urls = ( + "http://www.example.com/optimade", + "http://www.example.com/optimade", + "http://www.example.com/optimade", + "http://www.structures.com/optimade", + "https://www.links.org/optimade", + ) + results = [] + for request_url in request_urls: + results.append(get_base_url(request_url)) + + CONFIG.base_url = base_url_org + CONFIG.root_path = root_path_org + for i in range(len(base_urls)): + assert results[i] == base_urls[i]