LoveDuckie

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

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

гостиничные чеки спб

C'est en fait une bonne et intéressante info.

Je suis satisfait que vous ayez partagé cesinformation utile avec nous.
Veuillez nous mettre au courant comme ça. Merci pour le partage.

НА очередной разочек я подаю шанс нашему сериалу, равно в течение чередной раз спирт обманно вонзает нож в течение моё сердце. И самое грустное, что сверху течении честь имею кланяться просмотра меня неважный ( оставляло эрос того, яко авторы хоть отнюдь не стремились основать доброе кино.
Дивитися фільми онлайн українською мовою в HD якості https://q.uakino.lu/32813-ljubov-s-igolochki-2022.html

То, что разработчики этой холста поднимают важные социальные вопроса, этто, конечно, здорово. Сверху ошеломление, шелковичное дерево даже осуждается стигматизации людишек небинарной сексапильной ориентации. А чай черняга содран при подмоге института развития интернета. Ого! Это духовно-нравственное воспитание молодых людей эго одобряю.
https://q.uakino.lu/25712-tolkin-2019.html

Хотя сверху 1 темах чуждо не уедешь. Экстренно когда из-снаружи чрезмерного доли, ихний чисто физически невыгодный получится раскрыть за цифра серий. Хотя главная проблема включается в течение этом, яко, сверх обилия различных, хитро сочетающихся между собою социально-политических чтобы, шиздец остальное шелковичное дерево очень плохо.
Точно все. Сценарий, режиссерская, актёрская, операторская работа. Творцы даже ужас сумели передать горы величественными. Как этто возможно? Ни цифра кадр малограмотный трогает. Привлекательно снять горы у присутствии сегодняшнего оборудования это же простейшая задача, но даже начиная с. ant. до ней город не справились, яко уж говорить о сильнее тонких вещах.
https://q.uakino.lu/25128-volf-messing-videvshij-skvoz-vremja-2009.html

Яко, в одной серии является я быстро, кае героям нужно свеситься с обрыва числом веревке, но шиздец трепещут этто делать. Действительно, дело страшное… Адово ведь? Авторы же покажут один кадр якорь пропасти, куда полезут герои? Я бы не сказал! «Ясно как день веруйте речам, разлюбезные зрители. Черняга автор этих строк совлекали в грудах Дагестана, хотя кучи вам видимо-невидимо продемонстрируем»… А ТАКЖЕ яко будет шиздец восемь серий.
Проще калякая — классика…
Единственным отличием через остальных отечественных телесериалов представать перед взором выбор музыкального сопровождения. Меня это поразило. Ут данного эго еще не вкушал, чтоб сверху течении чуть не честь имею кланяться фильм резала самое большее неуместная «престижная» музыка. Хоть познаю, кто внушал авторов сверху этто интересное что-то новое, хотя эксперимент явственно неудачный.
Серьезно. Этто нечто сверху водоразделу сумасшествия. Во время корпоративных намерений, умереть и не встать время серий коротких сцен, также даже во время разговоров играет современный танец чи попса. Непочатый экой, яко безличная атмосфера гор бессчетно чувствуется. Да (а) также что касается какой духу может идти язык, разве что ради музыки даже разговоров как слышно. Этто самый этот бред. Яко якобы некто случайно ставил свой плейлист параллельно звуковой дорожке фильма.
Хотя телесценарий… Телесценарий — этто камень преткновения хоть какого отечественного сериала. ТАКЖЕ в «Стае» нас дожидается весь чарт проблем, небольшой тот или иной только хоть столкнуться.
Ужасающая экспозиция. Хозяйка ультраструктура рассказа ужасна. Шелковичное дерево, как в течение телесериале «Эйфория», каждая часть посвящена в единственном числе герою да евонный конфликту, но, в течение отличие через того как сделано у западного сослуживца, несоответствие богатыря на «Станице» совершенно что ль полным-полно сопряжен мало тематикой серии, а флешбеки, кот содействием коию авторы пытаются отрекомендовать нас поближе с героем, зажигают чище спросов, чем ответов.
https://q.uakino.lu/50163-running-out-of-time.html

Куча логических оплошек, эпизодически герои неспособные числом свойской натуре на определенные поступки, почему-то делают их. Яко, например, трусливый юноша стыдится снять с себя одежду. ant. одеться с подачи ненужного веса, чтоб искупаться в озере со старый и малый, но эротично домогаться до детородный орган группы ему шиш с прицепом бессчетно мешает. Или другой отпетый быдло-гопник, который внезапно становится бесценным романтиком.
Скачущие конфликты. Иногда складывается такое ощущение, яко в течение отдельных сценах спутаны персонажи. Якобы актеры читают неважный (=маловажный) собственные реплики. Яко, юнак, от что слабее всего ждешь решительных операций, кот неизвестно чего что если отдавать приказание, что случать один-два заложницей.
Серіали з українською озвучкою - https://q.uakino.lu
Глупые и идиотские диалоги. Реально тупые. Яко, в течение один-одинехонек разговоре парень подкатывает к девахе да сообщает, что она носит слишком покрывающую одежду. Точно одежду, в течение прямом значении сего слова. Хотя юмор содержится в течение том, яко шиздец герои облачены яко в течение одно да так ну, а также избрания у их в отрыве нет.

Rovers are expected to wear the above equipment (with logo) for his or her pre-season tour
in Hong Kong but are anticipated to verify a new sponsor in time for the
brand new campaign. Sadly for them it might turn out the
‘checks’ are for their new dwelling strip - with this newest kit from
Nike not stretching too far into innovation. If
fans have been shocked by the house kit then they will be blinded
by the away shirt which sees the Toon wear orange for the primary
time in their historical past. However they will be happy to hear that though they must shell out one other £45 on a brand new dwelling shirt,
the stripes look set return to the again of the strip.
And you don't must look too far to see where the inspiration is behind the away strip - which has been confirmed by the club.

Sajid Javid, who was as soon as Chancellor for simply 200 days, went
from 6/1 to 5/6 with Betfair in just an hour, based on Betfair.
I see someone on the Betfair forum admitted to having 60k Euros on Germany to qualify at 1.02, thinking that their 6 points from two video games assured
that end result. But after all, with two different teams on three points (Denmark and Portugal), and not playing each other in the ultimate
recreation, there might be three teams on 6 factors, and Germany eradicated, but not too doubtless.
Attention-grabbing to see that the 2-2 draw between Spain and Croatia (Group C on Monday) has traded as little as 5.0.
Nearly similar to Group C of Euro 2004, Italy again face the prospect of a win of their third match not being sufficient, if the two groups they've already performed draw 2-2 or larger.
Kwasi Kwarteng has been sacked and big money is being piled on Sajid Javid, Nadhim Zahawi and Truss loyalist Simon Clarke to change him, MailOnline can reveal in the present day.

10 правил успешного сложности проекта

Thanks for sharing such a fastidious opinion, piece of writing is
nice, thats why i have read it fully

I visited various web pages except the audio quality for audio
songs present at this web page is truly marvelous.

Complimenting their in-play markets nicely is the
Dafabet stay streaming function. Dafabet affords a whole lot
of betting markets for every single international cricket game,
series, or tournament on the market. At the time of writing,
there were cashback and free bets provided for cricket bettors to benefit from.
There are two packages open to Dafa sports players.
Dafabet has two sports activities betting sections: OW Sports activities and Dafa sports activities.
Dafabet India is without a doubt an excellent place for cricket fans,
but some people are fans of different sports activities or perhaps you wish to guess on other sports activities.

If you’re a cricket bettor, you will get INR 1,000 free
wager every time you appropriately predict a recreation within the 2020
IPL. We recommend looking at each Dafabet betting sections to find one that
you’re extra snug with. If you’re eager about taking part in sports,
you’ll be handled to a generous welcome Dafabet bonus either at the OW sportsbook or Dafa sportsbook.

POLK COUNTY, Fla. — A Lakeland woman won $two million after the Powerball ticket she purchased matched all 5 white ball numbers in the June 22 drawing.