Nginx – Map a url to a subdomain (NGINX)

configurationnginxsubdomain

I know this question has been asked before on SO but I'm having trouble replicating it on my server.

What I'm trying to do is when the user goes to medicine.example.com, the subdomain should be mapped to example.com/sites/medicine. So the URL the user sees is medicine.example.com. index.php is stripped off via php.

Ideally, the solution would be a wildcard/regex-based such that more than just medicine.example.com could be mapped to url.

The below code gives me a 502 bad gateway error.

server {
    listen      80;
    listen      443 ssl;
    server_name medicine.example.com;

    location / {
        rewrite             ^([^.]*[^/])$ $1/ permanent;
        proxy_pass_header   Set-Cookie;
        proxy_pass          https://example.com/sites$request_uri;
    }
}

Best Answer

You don't really want to proxy requests to the same webserver, it requires more overhead. I would configure a single virtual host for both domains, and use an if statement to only rewrite requests for the subdomain.

server {
    server_name example.com medicine.example.com;

    if ($host = "medicine.example.com") {
        rewrite . /sites/medicine$request_uri;
    }

    ...
}