Nginx using the wrong location block

Viewed 130

I have the following nginx configuration:

upstream front {
    server localhost:4000;
}
upstream back {
    server localhost:8000;
}

server {
  server_name my_domain.com;
  listen 80;

  location ~ /api($|/.*) {
    rewrite ^/api($|/.*) /VirtualHostBase/http/my_domain.com:80/Intk/VirtualHostRoot/_vh_api$1 break;
    proxy_pass http://back;
  }

  location ~ / {
    add_header Cache-Control "public";
    expires +1m;
    proxy_pass http://front;
  }

  location ~ /orgs/.+$ {
    return 301 http://my_domain.com/orgs;
  }

  location ~* manage_ {
    deny all;
  }

  location ~ \.php$ {
    return 410;
    access_log off;
  }

  location ~ ^/(wp-admin|wp-content) {
    return 410;
    access_log off;
  }

  location = /nginx_stub_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
  }

}

server {
  server_name www.my_domain.com;
  listen 80;
  access_log off;
  return 301 http://my_domain.com$request_uri;
}

I cannot understand what is wrong with it, specifically with the 3rd location block. If I write my_domain.com/orgs/some-org, shouldn't it redirect to my_domain.org/orgs? It's not doing that, it acts as if that location block wasn't there.

From my understanding, nginx should fulfill the request with the most specific match possible, and it should be the one in the 3rd location block.

1 Answers

http://example.com/orgs will be matched by location ~ / {} instead of location ~ /orgs/.+$ {}. Consider placing rewrite outside of location block, and use location / {} (non-regex without ~) as your fallback.

server {
  rewrite ~ ^/orgs/.+ /orgs permanent;

  # fallback
  location / {
  }
}
Related