0

In my nginx config file https-example.conf, it looks like this:

server {
    listen 443 proxy_protocol http2;

    server_name example;

    location / {
        return 301 https://www.example.com$request_uri;
    }
}

this means that for any request to example.com, it redirects to www.example.com. This is mostly fine but for reasons (external to me) I cannot change this behaviour.

However, there is a file called assetlinks.json that Google use to validate a web and android app are connected. This file should be accessible at example.com/.well-known/assetlinks.json and return a 200. However, it returns a 301 and redirects to www.example.com/.well-known/assetlinks.json which means google can't validate it.

I need to fix this behaviour. The file is actually hosted in an S3 bucket; in the https-www-example.conf file (where most config is handled), there is this block:

        location = /.well-known/assetlinks.json {
            proxy_pass http://s3-bucket.aws.com/files/.well-known/assetlinks.json;
        }

This works correctly (it serves the file at www.example.com/.well-known/assetlinks.json). I tried putting this block into the https-example.conf and it didn't work (still redirected to www.). ChatGPT suggested using location ^~ instead of location = which also didn't work. Finally, ChatGPT suggested replacing the return 301... line with this:

        location / {
            if ($request_uri !~* ^/.well-known/assetlinks.json$) {
                return 301 https://www.example.com$request_uri;
            }
        }

this works! it returns a 200 when I use a curl request on example.com/.well-known/assetlinks.json. It effectively only does the 301 redirect rule for paths that don't match ./well-known/assetlinks.json.

However, I don't like the conditional here; I know that's not best practice for nginx. Is there a better way to do this that doesn't need the conditional?

1
  • Please show full nginx configuration as shown by nginx -T command that did not work as expected. Commented Apr 26 at 6:37

1 Answer 1

0

Ok if I answer this correctly, please fire ChatGPT. Actually fire it for recommending "if" in Nginx anyway when it isn't necessary.

server {
  listen 443;
  server_name example.com;
  location = /.well-known/assetlinks.json {
      proxy_pass http://s3-bucket.aws.com/files/.well-known/assetlinks.json;
      break;
  }
  location / {
      return 301 https://www.example.com$request_uri;
  }
}
server {
  listen 443 proxy_protocol http2;
  server_name www.example.com;
  ...
  location / {
     ...

  }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .