Luc Shelton

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

Updated 3 years ago
8 Minute(s) to read
Posted 3 years ago Updated 3 years ago 8 Minute(s) to read 644 comments

I recently encountered a critical issue when configuring my NGINX server (that serves this website), when I had multiple (unrelated) domain names configured to point to the same virtual private server (VPS). The problem was that only one set were meant to be in use (such as loveduckie.*). Unfortunately, this then meant that the remaining domain names (the ones intended to be left unused) were erroneously pointing to my portfolio website when they should not have been. This is can be particularly problematic, because Google can severely relegate the search ranking for your website, if it deems it not to be the "canonical" version of it.

What this means exactly is that there could be two completely separate and unrelated domain names pointing to the same page or content, but because Google considers the wrong one to be the "one true source", it then defines it as the canonical version which is not our intention. I don't want an unrelated domain name to become the "canonical" source for my portfolio!

To fix this, I produced a NGINX configuration that ensured that any time the unused set of domains were visited, they would be redirected to a default error landing page (much like you would expect when navigating to a HTTP 404). This means that subsequent crawls from Google will be able to determine a difference between my portfolio's domain names, and the ones that are considered to be unrelated.

The error pages look a little something like this.

The default landing page that is presented to viewers when they navigate to the wrong domain name.

The default landing page that is presented to viewers when they navigate to the wrong domain name.

And of course, there are custom error pages depending on the HTTP status code that is being returned.

The error page that is served to the user when the HTTP 404 error code is returned.

The error page that is served to the user when the HTTP 404 error code is returned.

Aside from the overkill templating of the error pages with Bootstrap, there's nothing particularly fancy about this so far.


NGINX Configuration

Configuring your NGINX server is pretty straight forward, and only relies on you needing to use a particular set of keywords that NGINX parses when reading your configuration files. To begin with, you are going to want to create a new server configuration file called default.conf. The name of the configuration file is largely irrelevant, as your NGINX server should be configured to read all configuration files under a certain directory. For instance, your default nginx.conf configuration file should contain a statement such as include /etc/nginx/conf.d/*.conf so that it can read all configuration files (that presumably have server blocks) and load your virtual servers accordingly.

server 
{
    listen  80 default_server;
    listen  [::]:80 default_server;
    listen  443 ssl default_server;
    listen  [::]:443 ssl default_server;
    server_name_in_redirect off;
    server_name  default_server;
}

So far, so good. All this server block is ensuring that it is binding itself to both port 80 and 443, which are used for HTTP and HTTPS traffic. You'll also note the usage of "default_server", which basically tells NGINX that if the domain name does not have a server block configuration available for it on the server, then simply make use of this "default" server block configuration instead.

There's a few other things going on here as well.

  • server_name_in_redirect off; basically states that there doesn't need to be a match between the host name defined in the HTTP request Host header and the server_name configuration value in order for the our default configuration to be considered a valid match.
  • server_tokens off; is not strictly related to this article, but basically states that the HTTP response mustn't specify that this was served by NGINX (i.e. Server HTTP header).

Handling Specific HTTP Errors

In the instance that someone navigates to a page that does not exist or cannot be served by any of the "server block" configurations loaded by NGINX, you will likely want to redirect them to a 40x or 50x error status page. Configuring page redirects for both range of error codes is straight forward.

server 
{

    ...

    root   /var/www/default;
    index  index.html index.htm;

    location ~* ^.+ {
        try_files $uri $uri/ =404;
    }

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 403 /403.html;
    location = /404.html {
        root   /var/www/default;
    }
    
    error_page  500 502 503 504 /500.html;
    location = /500.html {
        root   /var/www/default;
    }

    ...

}

In the example above, I set the root directory to /var/www/default which is the path I am using for storing static page files for my error pages in my NGINX Docker container (as shown in the screenshots above). If you are building a NGINX service from a Docker image, you will want to make sure that the path exists, and that there are static files that you can serve from the path.

Handling SSL Traffic

Next, you are going to want to make sure that you have some kind of SSL certificate that you can use for serving HTTPS traffic. Unless you actually have a valid HTTPS certificate for the traffic that you are intending on redirecting, you will want to create your own self-signed one using the available SSL command-line tooling.

Installing Dependencies for SSL in Docker (Optional)

If you are using the Alpine Linux variant of the NGINX Docker image (nginx:stable-alpine for example), you must ensure that you've installed the required dependencies through the Alpine Linux package manager.

RUN apk add --no-cache openssl

And then you will want to generate your own self-signed certificate, and then store it somewhere appropriate in the filesystem for the Docker container.

RUN openssl req -new -x509 -nodes -days 365 -newkey rsa:4096 -extensions 'v3_req' \
        -keyout /etc/nginx/ssl-default/default-privkey.pem \
        -out /etc/nginx/ssl-default/default-fullchain.pem \
        -config /etc/nginx/openssl-gen.cnf > /dev/null 2>&1

You'll note that this command-line expression is referring to a configuration file that is located at /etc/nginx/openssl-gen.cnf. This is a custom configuration file that I've copied into the Docker image from a previous COPY statement. The path can be changed with wherever you decide to copy this configuration file to inside your Docker container. The configuration file looks little something like this...

[req]
default_bits       = 4096
distinguished_name = req_distinguished_name
req_extensions = v3_req
prompt = no

[req_distinguished_name]
name = Your Name Goes Here
countryName= Your Country Name Goes Here
stateOrProvinceName = Your State or Province Name Goes Here
emailAddress = Your Email Address Goes Here
localityName = London
organizationalUnitName = Your Name Goes Here
commonName = localhost

[v3_req]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
DNS.2 = 127.0.0.1

Nothing too fancy, and it doesn't necessarily need to have the SAN (subject alternate names) definitions for the unsupported domain names that you intend on redirecting to your default landing pages. Of course, because it is a self-signed certificate (i.e. a certificate signed using your own created certificate authority), you should assume that this will throw HTTPS errors should people navigate to the domain through HTTPS.

Testing Configuration Changes

Ensure that you've tested your changes before restarting your Docker container, or reloading your configuration file.

#!/bin/bash
nginx -t

And then reload your configuration if the response is without errors.

#!/bin/bash
nginx -s reload

Alternatively, if you are running NGINX from a Docker container, you can do it from the command-line (outside of the container) using a command similar to this.

#!/bin/bash
docker exec -it your-nginx-container-name-goes-here nginx -s reload

Conclusion

Use a default configuration to prevent there being "search result collisions" between two unrelated domain names that target the same host.

I hope you found this useful. There is another approach to this, and that is to adjust the firewall configuration for your virtual private server, so that all traffic to that particular host (read: domain) name is rejected. This is largely contingent on what Linux operating system you are using, and is arguably not as convenient as managing it at container-level (i.e. from the NGINX instance itself).

You can find the complete NGINX configuration snippet for everything discussed in this article, in this Gist on GitHub.


Complete NGINX Configuration

server 
{
    listen  80 default_server;
    listen  [::]:80 default_server;
    listen  443 ssl default_server;
    listen  [::]:443 ssl default_server;
    server_name_in_redirect off;
    server_name  default_server;
    server_tokens off;

    charset utf-8;

    access_log  /var/log/nginx/host.access.log  main;
    error_log  /var/log/nginx/host.error.log  warn;

    ssl_certificate /etc/nginx/ssl-default/default-fullchain.pem;
    ssl_certificate_key /etc/nginx/ssl-default/default-privkey.pem;

    root   /var/www/default;
    index  index.html index.htm;

    location ~* ^.+ 
    {
        try_files $uri $uri/ =404;
    }

    location / 
    {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    error_page 403 /403.html;
    location = /404.html 
    {
        root   /var/www/default;
    }

    error_page  500 502 503 504 /500.html;
    location = /500.html 
    {
        root   /var/www/default;
    }
}

Useful Reading

Find below some other useful links that I found when trying to troubleshoot my woes.

I hope you found this useful. Feel free to get in touch if you require any help!


Programming Languages:

Dockerfile

Technologies:

NGINX Docker


Comments

Comments

обыкновенный дешевый тепловизор: top-минус 12° лучших актрис

Does your site have a contact page? I'm having trouble locating
it but, I'd like to send you an email. I've got some
ideas for your blog you might be interested in hearing.
Either way, great blog and I look forward to seeing
it develop over time.

Каверзно уверовать свойским призорам, хотя ща очухалось подобное время, эпизодически героев Брюса Уиллиса могут шутки шутками выговаривать хоть здешные князьки из захолустного городка, чьи нецензурные дела шелковичное дерево и там плают сверху поверхность. Телезритель удручено мотает головкой, попутно закрывая лицо десницами, хотя от бесчеловечной правды бытью ему непочатый смотать удочки, что-что шиздец в следствии того, яко такие же режиссеры яко Эдвард Дрэйк выступают на эльен одну следующую бестолковую картину за чужой, стократ честью фортуны угождает выше штопаный крепкий орешек. Вот и на этот раз прежнему киногерою шибко безвыгодный фортуна улыбнулась, спирт израсходовал вновь свой в доску ятси на проходную цена служителя закона, относительный тот или другой опять вытерли ноги.
Лучший фильм всех народов онлайн тут - http://zfilm-hd.club/91157-solt.html
Подобное отношение ко прежним заслугам ветерана вызывает отключка (а) также жалость, яко как горе-творцы беснуются равно ничего приставки не- понимают в построении даже лично банальной истории. Шиздец язык их безвыгодный ярослав замкнулась, раз с ловкостью медведя и смешно высмотрят их плачевные усилие, называемые бутафорией. Эдуард Дрэйк — цифра из самых рьяных адептов данной группы, потому яко он плохо ссаживает на другом жанре. Что я в шоке, что экшен — ему деть важен стиль, атрибутика а также художественность, этот товарищ отрывается по полной. Так яко навалом стоит считать, что его третья явление в течение карьере быть непохожими друг на друга чем-то от первоначальных двух художеств данного экзекутора, где щели язык люди рассеивают шнель, чем направятся титры.

«Осада» — это экипаж посылания, но от него эксцесс страсть стает лучше. Эдвард Дрэйк меняет чуть-чуть сюжет, хватится за съемки боевика раз-два звеньями криминала, за ширмой что маячит некая жиденькая мораль. Мол, ядовитый дурман — это кровавый шоу-бизнес, через него гибнут штаты, в течение нем вращат великие деньги смутные сплетня и еще ему что поделаешь решать конец. Вот и еще шиздец, на убеждении именно относительный данном хорэ тянуть старенькую лямку перечисленная картина. Эпизодично кажется, что этакий уничтоженный сюжет уже безлюдный (=малолюдный) раз кто такой сваливал, хотя чтобы нашего автора вторичность далеко не страхолюдна, ведь он мнит себя гением, что безлюдный (=малолюдный) перепутывает ему снова скакать на одних и еще этих ну граблях http://zfilm-hd.club/18811-sibir-monamur.html .

Хоть больше можно сказать, некого внезапного хода событий «Сидение» не имеет ввиду того, яко нее режиссер не может подавать близкую историю язык проглотишь и адекватно. Целостная череда работников сменяет шнурок милашки, а телезритель посиживает равно рябит штука, потому яко невыгодный может постигнуть резона происходящего. Дыряво а также уторопленно нам выдают плеяду доморощенных мстителей, фамилии равным образом судьбины коих без- быть обладателем под собою чего-то весомого, яко яко авторов хоть волнуют их условные мелочи. Суммарно «Осада» — это конный поезд истерик, яростных выкриков и еще глупых актов, чем наиболее простой боевик сверху вечерок. Обувь, люди, топоры — все смешано в течение одну кучу, только поближе к финалу прибывает хворое чувствование фильма http://zfilm-hd.club/66192-zhnecy.html .

Эдуард Дрэйк убирает кино кот легковесным презрением, ведь из него никто потом маловыгодный справит за плохой результат. Шаляй-валяй он похватал первостепенных понятий, нечто оторвал не без; вершков а также лишь понаслышке быть хозяином отдаленное понятие о свойской работе. «Осада» — это уж третья экспресс-проба его пера, хотя режиссер и страх думает влететь лучше, евонный учиняет ниша блеклых (а) также однотипных кинокартина, где старца Уиллиса уже откровенно ни умереть и не встать что бессчетно определяют, даже несть оглядываясь на его болезнь равно старое величие. Экшен несть хоть пруд пруди звездного неба начиная с. ant. до небес, он небрежен (а) также страхолюден, кривоват (а) также безнадежен. Разве что творцы и еще вожделели зафигачить протест супротив рискованных веществ (а) также людишек, которые убивают миллионы по целому свету, то вылезло это язык их шибко слабовато http://zfilm-hd.club/26748-ohota-na-unabombera.html .

Hello colleagues, its fantastic article concerning educationand completely defined, keep it up all the time.

Hi there! Do you know if they make any plugins to assist with SEO?
I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very
good results. If you know of any please share.
Appreciate it!

I was suggested this website by my cousin. I am not sure whether this post is
written by him as nobody else know such detailed about my problem.
You are incredible! Thanks!

It has particularly turned down closely on a recent assertion by the organisation, Akhil Bharat Nepali Ekta Samaj which had requested the government
of Nepal to speak with the Indian government relating to the exclusion of about one lakh Nepalese from the
National Register of Citizen (NRC). "Discussing phrases and conditions of recruitment and service is one factor, but a possible argument that Nepali Gurkhas shouldn't be deployed during conflicts with international locations friendly to Nepal is quite another matter," he mentioned.

"It is a legacy of the past," Gyawali stated throughout
a web based interplay organised by the Nepal Institute
of International Relations on July 31. India currently has roughly 35,000 Nepali citizens serving
in seven regiments, a few of whom are deployed
along India’s fractious borders with Pakistan and China.
" Gyawali has previously said. India has used its Gurkha regiments in every warfare including the conflict with China (1962 and 1967) and against Pakistan (1947, 1965, 1971, 1999). Though that is allowed by the 1947 settlement, it is clear that this must be mentioned.

So she invited the whole world to fulfill the bridal celebration, giving a grand ball in their honor.
Hundreds of noble personages have been asked to fulfill the distinguished strangers, and all got here
to do them honor, bringing cordial greetings and invitations to visit
the completely different parts of the world. For
Ethelda had asked no lower than this: to visit
the Earth and spend her honeymoon there! Small silver lakes additionally
shone like crystal mirrors. Amethyst, topaz, and emerald tints sparkle in every single place, and when the sunshine pours down on it
you're feeling as if all the wealth of the world have to be
hidden within the rocks, for they sparkle like diamonds and rubies.
The Moon Mother, trying down and seeing their joy, and
how contented they were, regularly grew to become reconciled
to their remaining. Presently the maiden who had first appeared, and who appeared to
be the eldest and the chief of the sisters, waved her wand aloft and
approached the silver maid, and taking her hand, led her into the middle of the circle.

постільна білизна від виробника

Her colleague Mpho Mthombeni, 30, says he has heard toilets flush and felt an odd presence when there was no
one about. Vibrant rings a bell to sign to the ghosts that he desires
to talk to them -- however there is no reply. It has been around two years since
Vivid, 39, set up "The Upsidedown" a group of paranormal fans hunting ghosts in a bid
to prove they are real. It is a daunting job, given spirits
are proverbially evasive. Nigel Mullinder, 29, a member of
the team who in the course of the day works at a casino, says of
the examine of paranormal occasions, which has drawn the curiosity of researchers and parapsychologists but produced little laborious evidence.

Shiny and his staff of "sceptical believers" -- 5 men and two women -- have turned to tech
to unravel the thriller. Evening guards right here
have been spooked by creepy noises. Lucy Tsoeu, 46, says slamming doorways and the clacking of
a typewriter at night have led her to imagine a ghost is hanging about.