TransWikia.com

How to make Nginx redirect to 404 if subdomain doesn’t exist in localhost domain

Server Fault Asked by rplaurindo on January 29, 2021

This is my localhost server configuration for Nginx. This is at /etc/nginx/sites-enabled/development/localhost

server {
    listen 80 default_server;
    server_name localhost;
    root /var/www/html;
    index index.nginx-debian.html;

    location / {
      internal;
    }

    error_page 404 /404.html;
    location /404.html {
      root /var/www/html/errors;
      internal;
    }

}

If I call http://locahost in URL bar, a 404 page error is shown. But should show index.nginx-debian.html. But if I call http://localhost with a valid subdomain, it works. Like that http://users.localhost, defined in /etc/nginx/sites-enabled/development/users.

I want to show Nginx default page if I only call http://localhost, 404.html if subdomain doesn’t exist, and another any page if I call http://localhost correctly with a defined subdomain.

One Answer

I solved as follow.

At /etc/nginx/sites-enabled/development/default.

server {
  listen 80 default_server;
  server_name *.localhost *.<host-name>;
  root /var/www/html/errors/404;

  location / {
    index subdomain.html;
  }

}

At /etc/nginx/sites-enabled/development/localhost.

server {
    listen 80;
    server_name = localhost;
    root /var/www/html;
    index index.nginx-debian.html;

    # to URI errors caused by paths after domain
    error_page 404 /domain.html;
    location = /domain.html {
        root /var/www/html/errors/404;
        internal;
    }
}

I don’t know if this solution is the best, so if someone has a better solution, post here. Thanks.

Answered by rplaurindo on January 29, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP