nginx redirect argument
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I have nginx sitting in front of an app and need to proxy the request for sitemaps back to an api domain. here are the specifics

domain.com/sitemap.xml

should proxy to

api.domain.com/sitemap.xml

next we need to catch some of the sub sitemaps as well

domain.com/v1/sitemap-core.xml

should proxy to

api.1851franchise.com/v1/sitemap-core.xml

then we have other sub sitemaps like
/v1/sitemap-category.xml?id=4

/v1/sitemap-category.xml?id=6

/v1/sitemap-brands.xml

I think the best way to handle the sub sitemaps are to wildcard the path

domain.com/v1/*

and make sure to redirect the entire path with the id / query param to the proxy request to the api domain. we can lean on the exact match to domain.com/v1/ as the means for what we proxy vs leave alone.

awarded to dekkard
Tags
nginx

Crowdsource coding tasks.

2 Solutions


server {
listen 80;
server_name api.domain.com
}

server {
server_name domain.com
rewrite /sitemap.xml https://api.domain.com/sitemap.xml permanent;
rewrite /v1/(.*) https://api.domain.com/$1 permanent;

}

Winning solution

Hello, I think this should do:

location ~ ^/sitemap[^\/\?]*\.xml {
  return 301 $scheme://api.domain.com$request_uri;
}

location ~ ^/v1/sitemap[^\/\?]*\.xml {
  return 301 $scheme://api.1851franchise.com$request_uri;
}

This should handle only sitemap files together with the request parameters if any. The return 301 method should be more efficient than rewrite ... permanent as nginx won't have to parse another regex.

UPDATE

To proxy the requests you can use proxy_pass approach, something like:

location ~ ^/sitemap[^\/\?]*\.xml {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass $scheme://api.domain.com;
}

location ~ ^/v1/sitemap[^\/\?]*\.xml {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass $scheme://api.1851franchise.com;
}

(Instead of $scheme you can use http or https explicitly.)

a note, we dont want to redirect the user, we are proxying the request to the api in the backend. basically we are asking something via domain.com that is really on api.domain.com and with sitemaps we need them served from the main domain or google will complain a bit.
Qdev 10 days ago
Updated the answer with proxy_pass method
dekkard 10 days ago
View Timeline