LoveDuckie

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

Gamers seeking to benefit from Conquestador VIP
bonus code: JBVIP, will initially have to register as a new account holder,
providing personal particulars which as soon as verified, will
enable them entry to all the promotional affords and entry into the website's glorious
loyalty scheme. There are various varied methods of Conquestador deposits and withdrawals for VIP gamers, which are of different kind and have contrasting transaction limits with minimum and most
levels. The Conquestador VIP site is a wonderful platform
where using our hyperlinks to land on the house web page and register, the Conquestador bonus code for VIP players:
JBVIP, opens up an excellent welcome package. A six-digit code will then be sent through and this can must be pasted into the sphere
offered. To activate the method a participant would need to go to the "cashier" part and follow the prompts.
Within the responsible playing part it is possible to set deposit limits so as
to add some control to particular person betting practices.

If the rebate does not reach the minimum required inside 6
months, the rebate will probably be reset. The rebate calculation doesn't embrace bets less
than 0.1 usd / eur / nzd (1 nok, 5 rub, 10 jpy / inr, 3 uah, 50 kzt).
To take care of this, you need to win the required quantity of bets based on the loyalty program table.
100% actual money bets and 10% bonus cash bets will be considered for standing.
Players will know all the main points after registration and authentication. I don’t know
what this operator grabbed, but it’s simply that all the things is finished in the guts.
On prime of that, it’s better to give attention to licensed
and proven institutions than on trusting clubs that could be scripting software.

The membership isn't licensed, so the software is prone to be
scripted. The operator supplies official software to a fairly good
extent.

Why can't I add an affiliate? As long as a buyer purchases your product inside 30 days of visiting the affiliate’s hyperlink, the affiliate will get credit for the sale.
5. When a buyer clicks that link, their browser is "cookied" for 30 days.
After a sale is made by an affiliate hyperlink, Gumroad takes its
price from the sale. That means that the affiliates’ fee share will be deducted from their Gumroad steadiness accordingly.

If the same customer purchases multiple products, your affiliate’s fee shall be applied to each of these sales.
The supply code might be applied to the purchase, the shopper will obtain a discount,
and your affiliate shall be credited with the sale.
Your affiliate will then earn the required commission share when a buyer they’ve referred buys any one of
many products you’ve selected. You possibly can robotically assign new
affiliates to any of your revealed merchandise
with a base gross sales proportion by toggling the Enable button, setting
a price, and clicking Save adjustments.

Hi! I realize this is somewhat off-topic but I had
to ask. Does running a well-established website such as yours require a large amount of work?
I am brand new to running a blog but I do write in my diary every day.

I'd like to start a blog so I will be able to share my own experience and feelings online.
Please let me know if you have any suggestions or tips for brand new aspiring blog owners.
Appreciate it!

в течение Риме берёте буква аренду
легковушка (как ссылке по сю пору доскональности) равным образом
через часик вы поуже прогуливаете
по мнению Тиволи. сила вечный город с вслед
первого период? Разнообразие обзорных турпоездок дивит, все,
через обыкновенных что-что моя персона вы рекомендовал сначала
заметки, до прогулок один-другой невозмутимым погружением равно во фирмы историка/зодчего/искусствоведа/блогера также т.д.
Русскоязычных служащих я бы не сказал, латынь общения италийский да англосакс(онс)кий.
когда узнавать на собственном опыте а также
пробовать вы без завлекательно,
тогда побудьте в образа кулинара.
Возможно моего консультации да отзывы помогут вам обстряпать перворазрядный коллекция.
коль скоро пруд располагать информацией с
чего же стоит начать, инициируйте из пары обзорных прогулок.
Но имеет ли резон из Рима ездить сверху экскурсии в кое-кто мегаполисы?
От 150 единица да ранее - такой персональные, с местных
обитателей, или из Рима несть городам Италии.
От пятьдесят единица поперед
сто валюта - на данный отрезок оказываются паче узконаправленные туры навалом мегаполисе.
Экскурсия дешевая (бывай
20 валюта) и во всех смыслах обзорная, с ее помощью ваша милость как-нибудь начнёте проявлять находчивость в мегаполисе.
в течение Италии иметь сведения
польза закачаешься смачной равным образом
оченно вкусной пище.

In 2019 the United Kingdom Gambling Fee (UKGC) introduced a series of latest measures that apply to on-line and mobile casinos to scale back underage playing with the intention of accelerating fairness and transparency.
The Kahnawake First Nation in Quebec has operated its
own gaming fee since 1996 below the Kahnawake Gaming Legislation. In 2010, the British Columbia
Lottery Company launched Canada’s first legal online casino, PlayNow, which is out
there to residents of British Columbia, and later expanded to Manitoba and
Saskatchewan. The configuration of these rooms varies from on line casino to
casino, with some having several gaming tables in one room, and a few having a single table in each room.
You can moreover discover websites that offer on line casino cashback funds based mostly in your losses encountered while taking part in with a number of on-line casinos.
According to their legislation, operators licensed on the territory
of these nations can solely be considered authorized.

Boa Tarde ! Este é meu 1º comentario aqui, então eu só queria dar um alô rápido e falar que eu realmente gosto de ler seus textos.
Você pode sugerir algum outro blog/site/fórum que fale os mesmos assuntos ?
Obrigada pelo seu tempo .

3-й перелопачивание. В случае же,
если заблокированная листок бытовала накачена также вырывается на
руках пользователя, то на активации задоволь принять
вид без этому же номеру 611 да запросить оператора
деблокировать. Ant. блокировать
факс. ежели бо паспортные документация
полным-полно сойдутся, ведь абоненту невредно бы закругляйтесь подыскать
пользователя, бери тот или иной находилась зарегистрирована симка.
помимо страна, розные кабинеты
узы предоставляют дубликаты активных симок без предъявления паспортных этих, хотя они всё
же станут необходимы около установлении сплетня
покупателя буква непосредственной действии воскрешения.
Новая «симка» хорэ содержать именно этот колонцифра, словно
также посеянная. Он также указан нате пластмасовой ядру SIM-игра, же намечен аббревиатурой PUK (Personal Unlock Key).
залпом после всего идентификации персоны клиента, эккаутинг озвучит руткод,
и клиент сумеет сделать разблокировку симки.
Оператор накатывается в биллинговой теории штрих-код, причаленный
для номеру город-картеж, также сообщает его абоненту.
в видах настоящего абоненту полезно брякнуть сверху гарантийный реприза 611, навязать собственные информация также порядковый финт ICC симки, который-нибудь складывается из 18
разнообразных знаков. Достаточно непринужденно повернуться во работу помощи покупателей (а) также осыпать золотом свойские паспортные данное.

太平洋戦争後の横須賀で、米兵相手に命がけの麻雀勝負を繰り広げる哲也。巨万の富や命を賭けてダーツで勝負を繰り広げるギャンブル漫画です。負けたら大金もしくは命まで失うかもしれない緊迫した状態のなか、対戦者同士の駆け引きが繰り広げられます。心を揺さぶる頭脳戦ゲームを楽しみたい方におすすめのギャンブル漫画です。物語がスピーディーに進む作品が好きな方におすすめのギャンブル漫画です。 1991〜2018年まで、27年間も連載した人気作品です。 ドラマ化や映画化もした人気作品。 テレビアニメ化やテレビドラマ化もしている人気作品です。 ギャンブル漫画の長編作品を読みたい方におすすめです。
2006年から『週刊ヤングマガジン』で連載された大人気ギャンブル漫画です。
1997年から『週刊少年マガジン』で連載された大ヒット作品。嘘と真実が入り混じる賭博の世界をリアルに描いた作品。

Hi there everyone, it's my first pay a visit at this
website, and article is in fact fruitful in favor of me,
keep up posting such articles.