NGINX – Rewrite rules for subdomains

Ziyan Junaideen asked:

I have a SaaS web builder. Each tenant has a subdomain.

For business requirements, I am needing to give each tenant their own site map. The generation part is not the issue, but how to present it.

For the moment I have generated one index sitemap and a sitemap for each tenant.

$ ls public/sitemaps

What I am interested in doing is to make a rewrite rule that will make a request to to serve the file public/sitemaps/sitemap.tenant1.xml which is also accessible through at the moment.

Is this possible to do with a rewrite rule?


cat /etc/nginx/sites-enabled/

server {
    listen 80;
    return 301 https://$host$request_uri;

server {
  listen 80;
  return 301 $scheme://$request_uri;

upstream app {
    server localhost:3000 max_fails=3 fail_timeout=300;

server {
    listen 443 ssl;
    server_name *;

    root /var/www/app/public;

    ssl_certificate /etc/ssl/app.crt;
    ssl_certificate_key /etc/ssl/app.key;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
    ssl_dhparam ...;
    ssl_ciphers ...;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_stapling on;
    ssl_stapling_verify on;
    add_header Strict-Transport-Security max-age=15768000;
    server_tokens off;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;

My answer:

You’re using a catch-all server block to handle all of your subdomains. So, if you name your XML sitemap files using the actual subdomain name in the filename, then this gets very easy.

For instance, you may create a file Then you can load that file with a single location with an alias:

location = /sitemap.xml {
    alias /unix/path/to/sitemap.$host.xml;

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.