Drupal - How can I turn off caching redirect?
A response built from the RedirectReponse class is not cached. So you should not need to set any cache metadata (*). The problem here is probably the page cache for anonymous requests, which caches all responses, even redirects and no matter if they are cachable or not.
You can disable this cache by using the kill switch before returning the response:
\Drupal::service('page_cache_kill_switch')->trigger();
This will only disable the Internal Page Cache. To control caches outside of drupal, like proxies or browser caches, go to /admin/config/development/performance
and set a "Page cache maximum age".
(*)
On the basis of @Smartsheet eng's comment use LocalRedirectResponse
directly to prevent that RedirectResponse
might be converted to this response without cache metadata (which would be cacheable by default):
$response = new LocalRedirectResponse('/foo');
$response->getCacheableMetadata()->setCacheMaxAge(0);
You still need the kill switch because the Internal Page Cache doesn't process the cache max-age.