Jay
Jay

Reputation: 231

Redirect to new domain based on path in Haproxy

Hello and thanks ahead of time for the help.

I have a blog on my old site and I'm trying to 301 redirect all of the posts to their new location on my new site using haproxy. For example, I want https://www.oldsite.com/john-blog/blogpost1 to be 301 redirected to https://www.newsite.com/jill-blog/blogpost1.

https://www.oldsite.com/john-blog => https://www.newsite.com/jill-blog

frontend https
  option http-server-close
  reqadd X-Forwarded-Proto:\ https

  acl is_ob path_sub john-blog

  redirect location https://www.newsite.com/jill-blog code 301 if is_ob

I've figure out how to forward traffic for /john-blog but haven't been able to figure out how to do the rewrite so that /john-blog/blogpost1 on the old site 301s to /jill-blog/blogpost1 on the new site.

Upvotes: 2

Views: 14432

Answers (1)

JamesStewy
JamesStewy

Reputation: 1078

This is what I was able to come up with:

frontend https
    option http-server-close
    reqadd X-Forwarded-Proto:\ https

    acl old_site hdr(host) -i www.oldsite.com
    acl john_blog path_beg /john-blog
    acl jill_blog path_beg /jill-blog

    reqrep ^([^\ ]*\ /)john-blog(.*) \1jill-blog\2 if old_site john_blog
    redirect prefix https://www.newsite.com code 301 if old_site jill_blog

The only downside of this config is that it will also redirect https://www.oldsite.com/jill-blog => https://www.newsite.com/jill-blog. If this is an issue I can try and figure something else out.

How is works

I will follow and example for a request to https://www.oldsite.com/john-blog/blogpost1.

In this example acl old_site would be true, acl john_blog would be true and acl jill_blog would be false.

The reqrep line replaces john-blog with jill-blog only if both the old_site and john_blog acls are true, which for this example is the case. After this line the example url would be https://www.oldsite.com/jill-blog/blogpost1.

At this point acl john_blog is now no longer true but acl jill_blog is as the uri now begins with /jill-blog. acl old_site is still true.

The redirect line is in prefix mode where the redirect location is determined by the provided string with the original uri appended. In this example the provided string is https://www.newsite.com and the uri that gets appended is /jill-blog/blogpost1 resulting in a reditect url of https://www.newsite.com/jill-blog/blogpost1.

Hope that helps.

Upvotes: 6

Related Questions