I'm trying to mask an affiliate link, so I want to have a 302 redirect through nginx

I want to redirect all /go links to the respective affiliate link, so all link redirects would be like mydomain.com/go/affiliate redirects to > https://www.affiliatelink.com

Right now this is what I have

location /go {
                rewrite ^/affiliate$ https://www.affiliatelink.com redirect; 

I have tried everything and I cannot seem to be able to get it to work. Is there a specific file I need to do it on?

I have already tried both /sites-enabled/default and /conf.d/nginx.conf

New contributor
spacing is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Your rewrite doesn't work because the URL path you are requesting is /go/affiliate but the rewrite matches on the exact path /affiliate, which can never be found in location /go anyway. Fixing that is trivial and obvious, but for performance reasons you should avoid regex whenever possible.

Instead of this sort of rewrite, use one of two alternate approaches:

  1. If you have only a few URL paths to match, use a location for each one:

    location /go/affiliate {
        return 302 https://affiliate.example.com/;
  2. If you have a large number of links, I'd say more than 7 or so, use a map instead.

    map $uri $aff_redirect {
        default            "";
        "/go/affiliate"    "https://affiliate.example.com/";
        # more links

    A map goes in the http block outside of any server block.

    To use it, check for $aff_redirect variable in the appropriate server block.

    if ($aff_redirect) {
        return 302 $aff_redirect;
  • pastebin.com/J2PQKpqP this is my mydomain.com-ssl.conf, pastebin.com/HRHSW2nv this is my main nginx.conf , I commented out the Map function to test the other one, but I tried both. Also tried it on the normal config and the SSL version one, since the site is using https – spacing Feb 22 at 21:13
  • Finally got it to work. I had something wrong on my main nginx.conf. I wasn't able to get it to work with a map function tho. I don't know if that was because it was inside a HTTP tag and the site is https only. It only worked with multiple location tags like you described in sites-enabled/mydomain.com-ssl.conf, tried using the location tags in sites-enabled/default didn't work either – spacing yesterday

Your Answer

spacing is a new contributor. Be nice, and check out our Code of Conduct.

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.