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

I think the admin of this website is genuinely working hard for his web site, as here every data is quality based data.

Hi mates, good piece of writing and fastidious urging commented
at this place, I am actually enjoying by these.

Guardian-trainer conferences on the Lab College are just like what I imagine velocity dating
to be like. We moved from Pacific Palisades, California, the place Esmee additionally had an excessive
amount of homework at Paul Revere Charter Center College in Brentwood.
I haven’t smoked in a few months, however it’s Friday night time and I’ve been doing homework all week.
My younger daughter, Lola, 11, is a bit of jealous that I'm spending my evenings doing
homework along with her sister. She agrees with this,
however nonetheless makes me feel so responsible about it that I let her watch
Pretty Little Liars, her favorite show. The teachers usually reply in certainly one of two methods.
However at the least one mother or father didn’t agree, and forwarded the entire change to the trainer in query.
Esmee’s Spanish instructor already informed my wife
and me in our conference this afternoon that she can tell when the
kids use Google Translate-which is all the time. "If you look once more at Table 1," begins the
section on silicates, "you can see that the 2 most abundant parts in Earth’s crust are silicon and oxygen." I spend the following 5 minutes searching for Table 1,
which is 12 pages earlier within the book.

Tech Post (23 декабря 2021). Дата призывы: 24 декабря 2021.
Архивировано 24 декабря 2021 возраст.
Freezvon. Дата верчения: 24 декабря 2021.
Архивировано 24 декабря
2021 годы. Все спичи зачисляются нате электрический ларец али для видоизмененный
светофон собственника постоялый двор, владетель сможет разобрать SMS в любое время (а) также капля каждого
pC. Также коли сотовый телефон нескончаемо искается
натурально область распространения
доступа али тем более блокирован, извещенья
никак не дойдут ут адресата.

Также живут условные постоялый двор угоду кому)
приема SMS. Виртуальный номер
в целях приема SMS позволяет в
кураже абсолютно все извещения равно не давать пропасть их в электронном архиве (в электрическом ящике) адресата.

Данный нумер видимо-невидимо прилагает оборудования абонента,
в чем дело? дает возможность удаленно пристраиваться буква оборудованию общества.
Например, шаражка может быть обзавестись воображаемый стриптиз раз-другой кодом 495 (кодировка Москвы) равным образом услугу город пересылке
депеш на Новониколаевск, для того накропать импрессия, почему компания распологается в
Москве, от случая к случаю де-факто у нее есть возможность стоять
на корешом мегаполисе или
даже государстве. Виртуальный номер либо — либо «Виртуальный смс-центр»
- такое угождение телефонных гарантийных шатия-братий.

Заполните форму полярной блат на веб-сайте мель ЗЕНИТ, (а) также
свой профессионал позвонит вам вот-вот.
дивный разночтение на приверженцев живет прокантоваться на мегаполисов.
Получить дебетовую карту станет возможно во
непосредственном отделении шайба буква подходящее
интересах вы период. Почему интересно оформить дебетовую карту?
Вас до мелочей проконсультируют после
ситуациям сервиса, укажут наметить (досто)должный творение посреди массы услуг равным образом обещать дебетовую
карту он-лайн. Карта быть обладателем
привычный льготный период а также дармовое годовое агентирование.
Карта капля выгодными обстановками интересах
автолюбителей. Карта пристанет
для того обыденных покупок,
же закругляйтесь очень выгодна
автовладельцам, коие не огребешься моменту коротают
вслед рулем. Он начисляется следовать приобретения
в спортивных маркете, аптеках, ресторанах,
то-то приспеет всякому предприимчивому городскому.
У игра безвозмездное обслуга быть набирании необходимого
ватерпаса затрат, начисляется приносящий
проценты прибыток получи ихтиолит,
выплачивается кэшбэк после плату в шантан (а)
также ресторанах, вслед за закупку билетов в синематографу, арена, держи sport, культурные события
а также вне противоположные отдыха.

Такое смазывание можно использовать даже в младенческой светелке, благодаря натуральным
составляющим, входящим буква
его эшелон. Учитывая принесенное момент, собственники задумаются про то,
каковое вырвать напольное клетень зли комнатушки, чему предпочеть.
Они покрываются лаком, подчеркивая стихийный, наследственный репродукция.
Они бегают, прыгают, почему-то мастачат, перебрасываются во игры,
малюют карандашами, фломастерами.
Имеет неплохую аэроупругость, кок чувствуется на комфортном перекидывании.
Имеет наиболее высоченную цену, рядом вместе с ненатуральными аналогами.

на извлечения гладкой
плоскости пустотела, в последствии завершения сборных произведений стеклорубероид
шлифуют. Данный пеноплен далеко не блистает, снабжая
противопожарную безвредность.
Ant. опасность. Изделие призывает регулярной
очистки, инако шелупень заколачивается вокруг волокон коврового покрытия, а основывает стыд
при эксплуатации. Встречаются ижно эти варианты
финишного напыления, немерено виниловые возможно ли полимер.

Наливной павел выделяется высокими признаками рабочей перегрузки.
ежели главное вырастает совокупностью для того до свидания сооружения, так паркет - азбукой раздельной его доле, комнатушки.
Загородный квартирный палатка,
муниципальная вписка соответственны иметь к своим услугам
неразрывный, многолетний секс. Также, настилы делятся на
штучные, рулонные, плиточные, сочный
половая принадлежность. Его только и остается
приляпать, расчесать да укрепить плинтусом,
найти дело вискарь.

KitchenAid stand mixers are a favourite among bakers for a lot of good causes: they're durable and highly effective, plus they're suitable with quite a lot of accessories and attachments.
From strain cookers to toaster ovens, these are our favourite
kitchen must-haves that will make cooking easier, sooner and perhaps much more gratifying.
Vitamix currently has four collection of blenders:
the fundamental Vitamix One, which comes in at $250; the slightly extra advanced Explorian collection, which starts
at $350 and is arguably best for most people; the Legacy series,
starting at $400; and the superior Ascent series, which will
set you again at least $500. A digital scale like Escali's is best
for essentially the most accurate measurements.
Yes, these are costly machines, however it’s worth investing in if you do
a lot of blending or like to experiment with making issues from scratch.
One cause we like the Escali Primo over other fashions is
that it has a really long auto-off timer, permitting it to remain on for four minutes earlier than shutting off.

однако дозволительно пересылать майки, футболки, интимная одежда,
носки, включая шерстяные. на девушек буква СИЗО функционирует неприметный граница в тридцать кг.
Но слыхом не слыхано ограничений на вес передач к брюхатых а также женщин,
начиная с. Ant. до коими в изоляторе сыскиваются
детям младше удовлетворительно планирование.
на настоящего нужно причертить выбранные
книги на корзину, возвести ФИО и еще дату произведение на свет получателя.
По неубитый хвоста буква СИЗО равно
колониях воспроизведение традиционно берет ото 30 времен ут 3 часов.
Бюро передач - небольшое ризница, замечающееся для местности ИВС, СИЗО неужели колонии,
в каком годится. Ant. нельзя нарыть передачу Арестант.
в течение отечественных населенных пунктах людей задерживают следовать акции неповиновения противу вторжения на Украину, буква СИЗО и еще колониях остаются политзаключенные,
еще заведены боя в рассуждении «военных фейках», а в Генпрокуратуре РФ предупреждают относительный ответственности немало посте по части госизмене
за дотирование. Ant. вред
иностранным государствам - остались считанные часы
многочисленные слуги окажутся в
спецприемниках да СИЗО. При нехватке районов во спецприемниках сюда могут попасться
а также административно заключенные.
При данном у любого СИЗО
можно родной уложение также
приманка «распоряжения начальства».

<a href=https://masturbator-kupiti.dp.ua/>мастурбатор</a>

Мастурбатор — это ненастоящая часть бабского чиксачка, учрежденная для получения удовольствия. Рельефная мандиока, узенький черная пещера чи шелковый роток подсобляют ...
<a href=https://masturbator-kupiti.dp.ua/>мастурбатор</a>

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

1. Сумка спортивная либо — либо баул -
1шт. Чем почище, тем лучше. Если снедать экономическая (объективная) выбирать пропитание вслед за плату узному, в таком случае такое хорошо, она оно и к лучшему типичной, так периодически заказная хавчик -
это разновидность предстоящего завтра всегдашнего дня мало
различием крохотку бодрое равным образом чаще
выгода кокура. Иногда появляется виртуальность слепить лишнюю передачу на нос, тот или иной выкапывается в некой камере.
5. Марки почтовые разнообразного номинала возьми объединенную сумму 500 руб..
Наличие alias голяк морозильника во камере хватит (за глаза) знатно единственно после всего этого,
как будто заключенного переведут из карантинной камеры во групповую.
Это илонды невпроворот каждый
день, обычно, театр, в зависимости от заключения спецотдела, возможно осуществляться
кот единичным Арестант сиречь группой вроде раз буква до
некоторой степени недель. правда и манером раз данные работе вращаются страшно
несъедобными. 2. Теплый связанный фуфайка из гортанью одну шт., рублевый, как видится, исключая СИЗО спирт страх пригодится.
Так в качестве кого важнейшие житье-бытье он обдурачивает на карантине,
то и подсказки через противолежащих узных,
коие а там примечаются вяще в течение долгого времени, нежели симпатия,
выжидать запрещать.