Nginx: rewrite file from directory to root

Solution 1:

I don't see your full config and don't know, how and where do you include that sitemap.conf file, but I'd rather did it in a complete different way. With your existing map block it would look like

location = /sitemap.xml {
    # use '$domain' variable as a part of the full path to 'sitemap.xml' file
    root /var/www/domain/sitemaps/$domain; # no trailing slash here!
}

or even get the full path to /sitemaps/N/ folder with the map directive like

map $http_host $sitemap_path {
    www.example1.com      /var/www/example1.com/sitemaps/1;
    www.example2.com      /var/www/example1.com/sitemaps/2;
}

and

location = /sitemap.xml {
    # use '$sitemap_path' variable as the full path to 'sitemap.xml' file
    root $sitemap_path; # no trailing slash here!
}

If you still want to use the rewrite directive for this task, you are using it incorrectly. You can try this one:

if ($domain=1) {
    rewrite ^/sitemap\.xml$ /sitemaps/1/sitemap.xml last;
}
if ($domain=2) {
    rewrite ^/sitemap\.xml$ /sitemaps/2/sitemap.xml last;
}

or even more optimized:

if ($domain) {
    rewrite ^/sitemap\.xml$ /sitemaps/$domain/sitemap.xml last;
}