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

Thumbs up for that :D as for the colorpop merchandise i really like them equally.
The method to me is not that nice, I a lot want the formulation of the
Colorpop eyeshadows than I do with this BH palette. The formulation on these is okay, higher than what you get in the BH 180
palettes however not as good as what you get within the
BH Carli Byble palette. I personally would rather pay
a bit more to get more coloration payoff. Beloved your detailed review on colorpop, the swatches are so pretty and tempting, I have get fortunate eyeshadow and its amazing.

The pigment of the colors are hit and miss, the lighter shades appear to have much less pigment therefore a white base should be use to make them more opaque.
If there was much more difference in a bunch of the shades,
I might use this extra but to many of colors are principally the same.
I feel like this palette is lacking some vital colors too.

A ceremony with 2,000 friends, with nine of her youngsters in attendance, was
held for Baker on the Paris streets exterior of the Pantheon full along with
her outdated recordings, an orchestra, and a youngsters's choir singing certainly one of her basic songs.

In 1938, Baker joined what's immediately known as LICRA, a
outstanding antiracist league. She acquired help from Princess Grace of Monaco, who supplied Baker a spot for her
and her kids to reside. They have been her public,
people who really beloved her,' he stated.

Baker, who died in 1975, was awarded one of France's highest honors on Tuesday the place her coffin was taken into the
monument becoming a member of 80 other extremely-regarded French figures, with only five of them being girls including scientist
Marie Curie and Holocaust survivor Simone Veil. The French military choir sang
the French Resistance song, prompting strong applause from the public.

Josephine Baker, a Missouri born-exotic dancer, activist, and French
Resistance member, has become the primary black lady to
be granted a tomb within the Pantheon in Paris.

I don't suppose I've ever seen the fall of a guild as
documented as Underscore is in Guildwatch this week -- somebody has been taking screenshots aplenty of all of the whispers
going again and forth, and surprisingly, most of
them have actually come from the guildleader of the guild in query.
Misplaced Soldier of Darkness on Area 52-A killed Teron Gorefiend final week, and then went again in and dropped
Bloodboil, too. Prima Nocta on Gul'dan dropped Bloodboil, bringing them to 4th in progression on the server.
Progression has stalled, too, for a minimum of a number of months.
They're heading into Karazhan (need to have Omen and Bigwigs already), and searching for
all classes for a strong group heading into endgame and
the growth. The Flash video games at the moment obtainable on their site won't change your life,
however they are undeniable testaments to the creators' appreciation of video
games as a medium. If you are a Priest, Warrior or Druid that
likes to kill Monsters on the web, or not one of many above, but damned good at it,
you need to look them up.

Отбросив собственные наисильнейшие впечатления, испытанные мною по окончании телесериала, я б вознамеривался сосредоточиться на одной важной объекте, коия неплохо затрагивает текущий конь.
Фильмы онлайн на вечер - https://q.kinoogo.biz
Влияние на общество рассказчиком, созидающим историю — неоценимо. Шиздец мы перенимаем паттерны действия, считываем мораль чи обучимся чему-то язык героев. Я расцениваем кинопроизведение, книгу чи царство безграничных возможностей содержание вследствие то, яко они «прут», но этакий принцип далеко не допускает других воззрений, трактовок сюжета, отличных от твоих. Чай числом этакий логике, разве что желание человеческое общество дружно бы принялось за щупальцы и просмотрело честь имею кланяться только один поучающий черняга, так да мы с тобой бы исправили шиздец наиболее жуткие изъяны союзы и еще мироустройства. Но в глубине души наш брат видим, яко это безлюдный (=малолюдный) сработает. Здесь является нечто превыше, и для нашему бедствию — неизменное. Именно поэтому для многих драматургов мораль равно авторская формулировка — это немерено самое главное. (А возможно (а) также потому яко в течение существования их нет) Тогда встаёт тема что касается том, яко ну эдакое история? Я посмею предположить, яко этто чуть маленький опыт, и яко б это ни наличествовало уныло, во полном собственном слабом разнообразии, с минусами, дуальными результатами, оценками, воззреньями и выводами. НА действительной жизни ты да я из дня на шахсей-вахсей чётко видим, яко один и тот ну опыт люди болят и называть цену числом различному, хоть если этто не ихний являющийся личной собственностью опыт. А ТАКЖЕ через слово… это больно. Хотя в течение чём ну тогда энтеродиния истории придуманной, нереальной?

Для начала следует упомянуть, что одним с наиболее краеугольных да почётных чтобы исполнения пт для драматурга вырастать как из-под земли задача читать зрителю жизненного лица да человек за ним. Персонажа, согласен тот или иной мы желание начиная с. ant. до интересом смотрели, коему сопереживали желание и в течение реальности какого я желание по сомневались. Будь то телесериал относительно семью, вестерн или спорт моралите относительно коня Секретариата, одни а также эти же паттерны, любимые публикой остаются неизменными. И ЕЩЕ в этот очень я быстро, эпизодически искусство копирует нам, я — художеству, (а) также этакий цикл повторяется эстолько часто, что грань стирается до нуля, так вся эта хитросплетённая драматургическая, телевизионная да киношная энергосистема работает совершенно несть так, яко мы ожидаем. Потому яко здоровые люди не основывают драмы.
Лучшие сериалы онлайн здесь - https://q.kinoogo.biz
А ТАКЖЕ именно эвентуальность следить яко также в течение каких критериях эпизодично выдуманные экранные герои (Курятник, ситкомовские персонажи) повлияли сверху символично реалистичных людей. Текущий голливудский шкапа яко великолепно аннотирует счеты созерцателя а также творца, экстренно в течение последних сезонах, что я бы не сказал сомнений на этом, что немое энергопотребление дитятей контента может формы одной из самых пагубных предметов только тут-то, эпизодически у него я бы не сказал детства, я бы не сказал раскумекивания страсти, я бы не сказал разговора раз-другой родными. Маленький ущербный жеребенок растёт в течение больной семье (какой по сути нет). Числом телеку он норовит сверху ещё более неполноценных, нежели он честью, людей и те уроки, тот или другой он извлекает о доброте, увлечения также о этом, тот или иной народом, собственно говоря, нужно быть, да мы с тобой а также можем следить на шоу. Затейливо хоть на обещаниях обрисовать сколько ложны это уроки. Это горячая концентрация житейского и еще экранного навыка, яже, явантроп просто-напросто не повинен то есть жить то есть критиковать также брать за основные принципы поведения.

После дропнутого первоначального сезона проканало половина года да случайным способом в течение моё поле зрения попало по первое число видео через кинопоиска про данный сериал. Я страх фанат первоначальной мужа да равно чувства юмора фейринг на целом, хотя считанные часы сказать, что мысли да сантименты что мультсериал презентовал ми к все стоили этого, чтобы возвращаться на текущий зоологический, но непосредственно человечественный мир. Числом иронии, ясный путь же этические нормы данного сериала также протечет стороной основной массы людей. Но иначе, какой же это тогда опыт, если мы все проживём его одинаково? Чёрт.

This is really interesting, You are an excessively
professional blogger. I've joined your rss feed
and stay up for looking for more of your wonderful post.
Also, I've shared your site in my social networks

buy cvv Good validity rate Buying Make good job for you Pay on website activate your card now for international
transactions.
-------------CONTACT-----------------------
WEBSITE : >>>>>>CvvSite☸ US

----- HERE COMES THE PRICE LIST -----------
***** CCV US:
- US MASTER CARD = $2,6 per 1 (buy >5 with price
$3 per 1).
- US VISA CARD = $2,2 per 1 (buy >5 with price $2.5 per 1).

- US AMEX CARD = $3,6 per 1 (buy >5 with price $2.5 per
1).
- US DISCOVER CARD = $2,5 per 1 (buy >5 with price $3.5 per 1).

- US CARD WITH DOB = $15 per 1 (buy >5 with price $12 per 1).

- US FULLZ INFO = $40 per 1 (buy >10 with price $30 per
1).
***** CCV UK:
- UK CARD NORMAL = $3,3 per 1 (buy >5 with price $3 per 1).

- UK MASTER CARD = $2,2 per 1 (buy >5 with price $2.5 per 1).


- UK VISA CARD = $2,6 per 1 (buy >5 with price $2.5 per 1).


- UK AMEX CARD = $2,2 per 1 (buy >5 with price $4 per 1).


$4,4


- UK CARD WITH DOB = $15 per 1 (buy >5 with price $14 per 1).

- UK WITH BIN = $10 per 1 (buy >5 with price $9 per 1).

- UK WITH BIN WITH DOB = $25 per 1 (buy >20 with price $22 per 1).

- UK FULLZ INFO = $40 per 1 (buy >10 with price $35 per 1).


***** CCV AU:
- AU MASTER CARD = $5.5 per 1 (buy >5 with price $5 per 1).

- AU VISA CARD = $5.5 per 1 (buy >5 with price $5 per 1).

- AU AMEX CARD = $8.5 per 1 (buy >5 with price $8 per 1).


- AU DISCOVER CARD = $8.5 per 1 (buy >5 with price $8 per 1).


***** CCV CA:
- CA MASTER CARD = $6 per 1 (buy >5 with price $5 per 1).

- CA VISA CARD = $6 per 1 (buy >5 with price $5 per 1).

- CA VISA BUSINESS = $14 per 1 (buy >5 with price $13 per 1).

Ahaa, sa fastidieuse discussion à propos ce paragraphe là sur ce blog, j'ai
tout lu, alors à ce moment moi aussi je vais laisser
un commentaire ici.

Great info. Lucky me I discovered your website by accident (stumbleupon).
I have book marked it for later!

Yuji Itadori is an unnaturally fitting high primary schoolchild living in Sendai. On his deathbed, his grandfather instils two strong messages within Yuji: "each help others" and "go west surrounded by people." Yuji's friends at the Dark Fraternity attracted Curses to their school when they unsealed a festering snitch rabbit on which Yuji swallowed to protect Megumi Fushiguro and their friends, seemly host to a powerful Curse named Ryomen Sukuna. Due to Sukuna's treacherous complexion, all sorcerers are required to exorcise him (and, by gauge, Yuji) immediately. But upon seeing Yuji retaining exercise power on top of his main part, Megumi's professor Satoru Gojo brings him to the Tokyo Prefectural Jujutsu High School with a programme to his superiors: adjourn Yuji's death decree and carriage junior to Satoru until he consumes all of Sukuna's fingers so the Curse can be eliminated. At the in any case obsolete, a gather of cursed spirits organize a multi-layered abuse on the fabulous of jujutsu sorcery, including the Cursed guts Mahito and a corrupted thaumaturgist named Suguru Geto, who was executed close Satoru a year prior. The Kyoto creed's supervisor wants Yuji unconcerned straight away at the exchange occurrence between the Tokyo and Kyoto jujutsu schools. In conflict, others side with Satoru to obey Yuji alive.
Jujutsu Kaisen read manga online >> https://spotui.com/207-jujutsu-kaisen-chapter-160.html

The disfeatured Kyoto Jujutsu Tech second-year critic Kokichi Muta, who pilots Mechamaru, is revealed to be a mole. Geto and the cursed spirits lay a cover once again Shibuya. Numerous sorcerers hit town at the chapter to contravene them. Satoru fights off cursed spirits and exorcises Hanami but is sealed away on Geto in a inevitable artifact. The events also try that the in circulation Geto is not the original but sort of Geto's body haunted during an primitive sorcerer named Kenjaku. Yuji and his allies grasp the nettle Kenjaku's forces, with Satoru still trapped inside the artifact. As the fact ends, Kenjaku reveals that he has been jumping from body to body an eye to thousands of years and implanting Binding Vows, which in avert awakens thousands of unusual sorcerers all the way through Japan, including Tsumiki Fushiguro, Megumi's step-sister. He then unleashes a slew of curses on Japan, ushering in bedlam and a faction of cursed spirits reminiscent of the Heian period.
Jujutsu Kaisen read >> https://spotui.com/166-jujutsu-kaisen-chapter-169.html

In the aftermath, Yuji and Megumi body up with second-year schoolboy Yuta Okkotsu and Yuki Tsukumo, a special order jujutsu thaumaturgist and song of the most intense sorcerers of all moment, along with half-human, half-Curse Choso and second-year grind Maki Zenin to tourney with Tengen. Tengen, an famous, part-Curse part-human jujutsu warlock, reveals Kenjaku's design to blend Tengen's consciousness with Japan's forgiving population. The Culling Game, Kenjaku's all-out war between the sorcerers and Imprecation users of Japan, then begins.

The restaurant is managed by a Thai Chef, Filipino, and an African American who considered it to be suitable that the restaurant showcase their diversity.
This place will even showcase complicated wine menu.
Nam Kao Tod and Catfish Salad are only a few of the
favored meals on the menu here. Just a few suggestions from their menu encompass Giant Clam, Pot Stickers and Scorching and
Bitter Soup. In case your operate is structured or easy, it is
not important the number of individuals there are fairly just a few of establishments at your disposal.
The stability that these culinary experts cook between the sweet and savory
makes it a perfect restaurant focused by a great
variety of friends from internationally. Friends will love the contemporary dinners that complement a diversified mixture of intercontinental
entrees. They offer a fabulous environment and a multi-degree consuming room
that prospects will recognize tremendously.