Why can't we stop going to the root?

So i’m trying to help someone figure out why their NGINX server keeps serving people the root document. We’ve tried several versions of the server config file, which is currently as listed below.

The expected behavior, from my understanding of the NGINX config setup, should be:

  1. If the address has a subdomain, 404 it.
  2. If the address is an HTTP connection, repoint it to HTTPS.
  3. If the URL contains the /panel, panel1, or panel2 directories, redirect them to the appropriate port.
  4. Default, serve from primary root.
server {
  listen 80;
  listen [::]:80;
  listen 443;
  listen [::]:443;
  server_name ~^.+(?<!www\.)nameredacted\.com$;
  error_page 404 https://nameredacted.com/404.html;
  return 404;
}

server {

  listen 443 default_server;
  listen [::]:443 default_server;

  ssl on;
  ssl_certificate /etc/nginx/ssl/nameredacted.crt;
  ssl_certificate_key /etc/nginx/ssl/nameredacted.key;

  root /home/nginx/www/html/nameredacted;

  error_page 404 https://nameredacted.com/404.html;
  index index.html;
  server_name .nameredacted.com www.nameredacted.com;
  location / {

    try_files $uri $uri/ =404;

  }

  location /panel {

  rewrite ^/panel$ https://www.nameredacted.com:8080 redirect;

  }

  location /panel1 {

  rewrite ^/panel1$ https://www.nameredacted.com:8081 redirect;

  }

  location /panel2 {

  rewrite ^/panel2$ https://www.nameredacted.com:8082 redirect;

  }

}

server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name .nameredacted.com www.nameredacted.com;
  rewrite ^ https://$host$request_uri? permanent;
}

2,3, and 4 all work. #1 is giving us grief. Am I missing something obvious?

I realise this is a bit of an old thread, but I’d like to answer all the same :slight_smile:

The problem here is the way is how nginx resolves which server to use, which is in fact a lot easier than you seem to assume, as it will first check any exact match, and only then continue to check for wildcards. So it will not try your servers from top to bottom, but load everything in memory and then find the best match given the request hostname and the server_names it holds in memory.

So for your case you should have one server for nameredacted.com and www.nameredacted.com and another server for *.nameredacted.com that will catch any requests for any non-www subdomain.

Source: http://nginx.org/en/docs/http/server_names.html

Also, you can use return instead of rewrite for all your cases, e.g.,

location /panel2 {
  rewrite ^/panel2$ https://www.nameredacted.com:8082 redirect;
}

becomes

location /panel2 {
  return 301 https://www.nameredacted.com:8082;
}

etc.

Short and sweet :slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.