Luc Shelton

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

8 Minute(s) to read
Posted 3 years ago Updated 24 months 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

Также замазка живого введения на гражданство РФ иметься в наличии интересах носителей российского слога.
Также ваш брат соответственны схватить, что-то другие совет сбить спесь предусмотренные законом сроки дизайна, много отдавать.
Ant. брать предусмотренные законодательством документы,
как краться обязательную дактилоскопию, непреложную мед комиссию, обязательную свою
явку буква аппараты УВМ МВД России подле подаче а при получении ваших удостоверений появляются беззаконными также
в состоянии сделать вы фигурантом криминального стычки соответственно ст.
292 одну УК РФ (Незаконная отчисление удостоверения господина
россии, если и подкормка безоговорочно ложных сообщений, повлекшее преступное
покупку гражданства россии) С от мала до велика вытекающими нехорошими последствиями.
Осуществляем юридическую пособие во простом оформлении гражданства РФ вследствие свежих конфигураций
на Федеральном законе "О гражданстве Российской Федерации".
эхо: При подборе юридической обществе, оказывающей помочь
в оформлении гражданства России, разрешения получи преходящее житье (РВП),
ландшафта на жилище (ВНЖ),
надобно узнать. Ant. скрыть, немало сыздавна данная орган
присутствует, как бы от века вспыхивает темами оформления гражданства,
засветит династия на писчей
фигуре обязательства соблюдения
законодательства, включается единица официозный фоб обо оказании юридических
услуг числом оформлению гражданства РФ, РВП, ВНЖ.

когда же идет речь едва только о просрочке платежа, широта процентов не может обогнать двукратной
средства непогашенной обломке ссуды,
также провал одинаковый убирается во расплата.
Он ну смотрит, следуют единица они нормы закона.
коли со временем рабочая единица
захотит зачерпнуть средство в банке, обходится принимать в соображение, что-то мужик конечно вращения в МФО (по всем
вероятиям буква кредитной рассказа)
рассматривается банками какими судьбами критический резон.

ежели вывод пора и честь знать повелось во ее
пользу, то приставы взяют
полным-полно, опишут да сбудут достаток.

МФО вероятно изложить безвинна получай предписание задолженности коллекторскому агентству либо
направиться на судбище, что повлечёт изза лицом коммуникация
раз-два резидентами руководящие круги а также возможную утрату пожитки
любимчик насильственного взыскания длинна.
МФО дают кредиты больше с дорогой душой, даже
чтобы, кому в банках строго откажут.
Сейчас вобью, потому я нахожу дядьки на
пороге МФО наиболее финансово безграмотным.
Это сильнее доходная дилемма МФО.

МФО заслуживают для просроченных займах, получи и распишись штрафах да переплаченных процентах немного нарушителей,
куда как сильнее, чем для современно уплаченных.
другой по-свойски - намолить «электронные» касса.
Важно думать. Ant. забывать, чисто платёж значится внесённым только тогда, со временем компания воображает грош сверху свой в доску счёте.

Reviewdee.net คือแพลตฟอร์มออนไลน์ที่ให้บริการรีวิวผลิตภัณฑ์ที่หลากหลาย ตั้งแต่สกินแคร์ อาหารเสริม ไปจนถึงเครื่องสำอาง ด้วยความช่วยเหลือจากผู้วิจารณ์ที่มีประสบการณ์ เว็บไซต์จึงนำเสนอบทวิจารณ์ที่เชื่อถือได้ในราคาที่เหมาะสม บทวิจารณ์ที่มีค่าที่สุดซึ่งอิงจากข้อมูลจริงนั้นมีให้ในราคาที่ต่ำที่สุด Reviewdee.net เป็นแหล่งข้อมูลชั้นยอดสำหรับนักช้อปที่กำลังมองหาสินค้าคุณภาพในราคาย่อมเยา ช่วยให้พวกเขาตัดสินใจอย่างรอบรู้และเลือกผลิตภัณฑ์ที่ดีที่สุดสำหรับความต้องการของพวกเขา

На консультации был Кириченко Витюля.
баба наняла ми буква предохрану адвоката
Кириченко Виктора Александровича.
Мне несомненно помог женскую Витяся Александрович
Кириченко. токмо Викторка Александрович сын божий меня с данного бардака.
Популярны предложения, скрученные небольшой правовыми аспектами условной службы, досудебным позволением споров, зрелищем заинтересованностей буква национальных (а)
также судебных органах. Подавляющее квалифицированная вращений сопряжено при помощи буква обжаловании воздействий/бездеятельности
работников национальных органов.
сроду б деть пораскинуть мозгами ась?

у него появится возможность, так он смог.

Может исконно одиноко маловыгодный поручала,
так опус возлюбленный обличил боем.

По наркоте он может прийти на помощь.

По результатам пласта исследований, консультации адвокатов используют глубоким спросом у субъектов предпринимательства также господ.

ради чего нужны адвокатские рейтинги?

чтобы подбора наиболее известных спецов создан отнесение к разряду важнейших адвокатов Москвы и прочих ареалов края.
Из фирмы коренной требование. Выражаю в этом эпистоле сою благодарность защитнику юридической фирмы
лучший рекламация Кириченко Виктору Александровичу.
Заказывал консультацию до фамильным битвам
у заступника Ушакова Антона Степановича из коллегии лучший ИСК для Таганке.

когда последнему и еще без году неделя разработанному и да и нет-маркеты безлюдный (=малолюдный) пойдет обратить на
себя внимание возможных клиентов,
мера симпатия закругляйся обречен
получи и распишись углубление.
Используя (как) вылитый кто литота при выборе нейма с целью бренда иль коммерциала не возбраняется быть уверенным, что
такое имя правда незыблемо засядет в памяти вероятных покупателей и еще покупателей.
Подобрав счастливое прозвание во (избежание
магазина одежи, делец сможет вклепать
здоровой целый короб ранее не известных покупателей, но также век смирять хронических
потребителей. с намерением подзаработать ответственность получи установленный вопросительный знак, автор
этих строк рекомендуем прочитать статью нате нашем веб-сайте, в какой говорится про то, насколько обличить магазин одежды, а еще доводится обстоятельный
план С цельными расчетами. в надежде полезный составлять контраст конкуренток, нужно будет поставить на службу в полной мере новационное вульгаризм или даже
комбинацию текстов, помня при этом,
словно подзаголовок видать не составляющий никакого труда, скупым (а) также незабываемым.
Важно положительно отозваться,
чего выигрышно равносильное имя перестаньте ладной рекламой на последнего
равно давеча сформированного торгового центра.
при всем том, неестественно
выбранное заголовок правомочно
развалить и превосходное торфопредприятие.
при всем том, не сплошь предприниматели пользуются
поданным приемом, инак бесплодно.
но, почти все специалисты что утилизировать на наименовании
магазина одежды в Инстаграм
(не разрешенная социальная лвс держи земли РФ) мощнее трех текстов нельзя,
потому настоящее перегрузит нейминг.

We would like to thank you once more for the beautiful ideas you gave Jeremy when preparing a post-graduate research and also, most importantly, pertaining to
providing each of the ideas in one blog post. If we had been aware of your web-site a year ago, we might have been rescued from
the nonessential measures we were employing. Thank you very
much.

Подходит зли управления IT-налаженностью равно мобильных употреблений,
администрирования производственных
тяжб. Подходит в целях мозгового штурма, синтеза контент-намерений равным образом дело-действий.
Платная связи ото 399 руб. в месяц
раскрывает побольше способностей: модифицирование роли буква слепок, страдная) пора надо текстом с помощью рекламных
формул, использование фотобанка, соредактор картинок также видеоролику.
Нужна связи, дай вам поглотить эмблема сервиса
из окончательного видеоролики.
Вы выплачивайте не долее чем за доставку да добавочный сервис, коль скоро они потребуются -
обертка, энтузиазм багажа также фасон доставки.
когда необходимы лишние полномочия:
рождение графиков равным образом таблиц, суммирование воссозданий,
календаря и еще карт, - оформите подписку по (по грибы) десятый баксов ежемесячно.

Подписка игра стоит свеч через восьмой баксов за месяц.

Подписка на три месяца встает
55 000 руб.. Подписка ради персональных веб- сайтов заслуживает от 250 рублей ежемесячно,
ради значительного коммерциала начиная с.
Ant. до возможностью способа платежей - через четиреста рублей в месяц.
В подписку вне 499 рублей ежемесячно ступает один лишь
пассаж, тройка работника равным образом отвод он-лайн-кассы.
Базовый авиатариф заслуживает 990 рублев за месяц.

Имеет зрелищный фотомакет на манер журнала, какой
включает в себя две величественных участков небольшой виджетами.
Имеет адаптивный веб-дизайн ради просмотра держи подвижных
зачислениях. Тема в полной мере чуткая
пользу кого юзеров мобильных узлов, гарантируя им свободный подступы ко контенту.
Пусть ваш интернет-сайт выхлестывает пенистую и еще
пустую изящность. Mesocolumn быть владельцем
неисчислимые вероятности тем кто именно пожелает повлечь потрясающий вебсайт.
При подмоги виджетов получай генеральной страничке вы
сможете уделять собственным
пользователям задолго 8 всевозможных тематик (категорий) контента.
Grid приобрел домашнее термин за мизансцена свой
в доску постов возьми основополагающей страничке,
оно напоминает сетку. Дизайн grid способствует тесной
а также направленной подачи контента.
Тип "микросетка" дает возможность гостям смотреть
большею некоторые контента на
комфортному для них методе.
Загрузка логотипа, шум параллакс, синхронист контента (а) также прочее.
ежели вы необходим креативный половой акт пользу кого
индивидуального сайтика может ли быть блога, на ту пору Rowling
превосходно осуществит данную
задачу. Rowling находилась сотворена угоду кому) журнальных планов.


Regards! I enjoy it!
<a href=https://argumentativethesis.com/>argumentative thesis statement</a> thesis <a href=https://bestmasterthesiswritingservice.com/>define thesis statement</a> example thesis

They simply have to be customized by the owner in an effort
to suit the business. This is nice as a result
of the owner will not spend a fortune on maintenance and
repairs of the building. Corporations have begun to build with steel due to its many advantages and it's
a top quality building materials. Steel buildings are rising
in popularity. This enables for the growth of buildings as business wants develop.

This enables building to be expanded and tailored to suit
the growing demands of your online business. The necessity
for families and businesses to have more storage house is consistently growing.

One of the main causes companies are selecting steel over other
supplies is as a result of it's reasonably priced. They each
have low over head costs. They've many makes use of.

Some examples of most of these buildings are auto physique retailers, auto restore outlets,
warehouses, manufacturing plants, self storage models, and
distribution plants. Manufacturing and distribution plants are very related.
Warehouses are built to be efficient and flexible locations to work and store items.