redirect to url only if the destination url is valid

Bogdan asked:

I have a redirect rule setup like this

#redirect old phpbb links to xenforo links
if ( $arg_p ) {
   rewrite ^/forum/viewtopic.php /forum/posts/$arg_p/? permanent;
}

Which it will send a 301 to any url that matches that regex to the new format.

However I would like to know if there’s a way to do this redirect ONLY if the destination URL is valid (in this context valid means it should not return a 404 or 403)

My answer:


You can’t really do this easily, and it’s unlikely that you really want to.

If you could do this, it would require a query to your web application for every single incoming request, in addition to serving the request itself, thus approximately doubling the load on your server. This could probably be done with some clever embedded Lua code, but I think you probably don’t want to overload your server.

Better to just redirect everything and then let the destination (your new forum) serve a 404 if necessary. This doesn’t really have any SEO impact, because the original links were 404s already. But it provides a better user experience, since incoming traffic to dead links will at least see the new forum rather than a plain white nginx 404 page.


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.