We have a staging environment for our rails webapp set up as a second Apache virtual host, with haproxy 1.5 sitting in front of both. Until recently the stage was configured as a different frontend listening on a different port to the live version. This worked pretty well as any redirections, links etc. worked perfectly, with all traffic just going through a different port.

However, we're adding https redirection to the site; this breaks the port-based strategy as the http and https listen on different ports (so http://www.example.com:3000 gets redirected to https://www.example.com:3000 which breaks if you're listening for ssl on e.g. 443.

I tried a similar setup to the author of this post: HAProxy reqrep remove URI on backend request

That is to say, I've configured a single haproxy frontend to use the "stage" backend if I insert /stage/ into my url, so:


serves the page from the live backend, whilst


serves the page from the stage backend. Because I obviously want to run apps with an identical directory structure on both backends, I'm stripping away the "/stage/" from the URI in the stage backend. The problem is that any time the rails app itself wants to redirect me (if I even click on a link!), the stage is no longer in the url, so it redirects me to the live website. The idea of the setup is that the app can just be copied from stage to live once we're done testing, so I don't want my Ruby code to know or care which environment it is in if I can avoid it. Is there any way (within haproxy or apache) so that any http requests made by that version are "kept in-house", so that if I log in to the stager version I stay there?

Thanks in advance.


I wouldn't look into different URL, subdir, port or anything like that if you want to set up a staging environment. Instead I could recommend 2 different approaches which do not require any URL rewriting.

  1. You could set up the frontend for the staging environment on a different IP address. In case you want to test the staging environment, you could simply point the (sub-)domains to the staging IP in your local hosts file. This approach requires you to have an IP address available of course.

  2. You could set up an ACL in HAProxy based on a cookie set on the domain. If you enable the cookie, you will be sent to the staging environment. In HAProxy config this would look something like this:

    frontend main
    [... bind stuff ...]
    acl staging_cookie_set req.cook(enableStaging) -m str 1
    [... rest of your frontend logic ...]
    use_backend staging if staging_cookie_set
    default_backend live

    If you now set the cookie 'enableStaging' to '1', you will be sent to the staging environment.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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