3

I am trying to update htaccess to write as following:

htaccess sitemap.xml rewrite to /sitemaps/$_SERVER["MYVAR"]/sitemap.xml

This rewrite should only occur if sitemap.xml is requested in root (otherwise the above would loop)

I came up with this

RewriteCond %{REQUEST_URI} !^/sitemap.xml
RewriteRule .* /sitemaps/$_SERVER["MYVAR"]/sitemap.xml [L,NC]

But this is not working, server error. Anyone know how to do this?


And on a side note: rewrite to /sitemaps/domain/sitemap.xml would be fine too (where domain is captured from the request host either www.domain.com or domain.com)

1 Answer 1

1

You can't use a PHP superglobal eg. $_SERVER["MYVAR"] in an htaccess expression. (Apache .htaccess files are processed before PHP gets a go, but anyway $_SERVER["MYVAR"] is PHP syntax not Apache mod_rewrite syntax). However, depending on what MYVAR contains, there might be an alternative.

This rewrite should only occur if sitemap.xml is requested

Your current RewriteCond directive actually does the complete opposite and results in a rewrite when "sitemap.xml" is not requested. The ! prefix negates the regex.

rewrite to /sitemaps/domain/sitemap.xml would be fine too (where domain is captured from the request host either www.domain.com or domain.com)

This is possible, something like the following:

RewriteCond %(HTTP_HOST) (www\.)?([a-z0-9-]+)\.com
RewriteRule ^sitemap\.xml /sitemaps/%2/sitemap.xml [L,NC]

Where %2 is the 2nd parenthesised sub pattern in the RewriteCond directive. However, before this you should already have your canonical www or non-www redirect, so you should already know whether HTTP_HOST contains the www subdomain or not - this will simplify your RewriteCond pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.