Luc Shelton

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

NGINX: Default Server Configurations

Updated 7 months ago
8 Minute(s) to read
Posted 17 months ago Updated 7 months ago 8 Minute(s) to read 222 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

In March of 2018 the official 123Movies web site shut down, with a notice
on their homepage stating “respect filmmakers by paying for films and
TV-shows”.

The game gained Best Visual Design, Best Multiplayer Game, Critics' Choice Awards, and
Ultimate Game of the Year.

One evening I did that, ran the blood, got the values printed out,
and abruptly blanked out. I'm teaching myself bass and keyboard and intend to spend a minimum of one hour a day with every instrument.
Billstop24 is considered one of the most important online casino
where you'll find lot of casino video games. Actually on line casino games
are gambling video games. Bill's contributions and dedication to his community and country are impressive for any
seasoned professional, not to mention someone living with a disease that monkeywrenches a person's thinking, reminiscence and conduct.
I additionally drew arterial blood to be analyzed as a way to set the parameters
on the machine to greatest help the affected person. An instance of the
"little things" that went on about 6 years in the past: I lived
alone in an house and was on the lookout for a selected china plate,
which belonged to a set I had inherited from my mom.
I've now been unable to work for three years and am thought-about disabled.

Do you depart enough margin in your life for some down time?
Help them formulate an emergency exit plan when their defences are down. The chemicals act as if they're bonding, attaching
and sexually experiencing the second. Filters, limits and boundaries are crucial for it to go nicely with
technology in your home. Implementing limits could be tiring, divisive,
however important. Researcher J. Dennis Fortenberry identifies four areas of sexuality you should use to information conversations along with your
kids. When kids are aroused, lonely, offended, bored
or upset, choice-making can take a unsuitable
flip fast and danger-taking can turn out to be damaging. Wholesome risk taking might be enjoyable and
dangers aren’t necessarily unhealthy, it simply will
depend on which dangers an individual chooses to pursue.
Now, this doesn’t mean it is good or bad, it just implies that teens need steerage on the
way to wisely handle this season of life.

There is a particular 4Rabet promo code of 4RATOPBET,4RABETOP for Bangladesh,
which you have to enter in a special field on the registration page.
Also post your questions on this web page in the event
you can’t find an answer here! Our specialists will quickly and politely reply any of your questions and repair the issue, if any.
The 4Rabet support team can answer you in Bengali and different
languages and reply to your requests inside
quarter-hour for emails and in a number of seconds in dwell
chat. Gamers can withdraw jackpots from their stability with out
wagering necessities or other hassles. To start betting,
you will need to have an account with money on steadiness.

You do not need something apart from a personal account and cash in your gaming stability to
make bets. For multi-betting, merely open the reside section and
make fast selections by scrolling by way of the various matches and clicking on the suitable outcomes.

Deposit £10 or extra to Casino at bet365 and choose the
Declare box. Stake £10 on eligible On line
casino video games and accept your 50 Free Spins. Tickets and prize wheel spins expire after seven days.

Sign-up with the Bet365 On line casino, where you'll be able to
obtain a welcome provide of fifty spins on selected video games.
These free spins can be utilized on chosen games together with 'Joker
Rush,' 'Age of Gods - E-book of Oracle,' and 'Legacy of
the Tiger.' A full checklist is offered on their site.

Full particulars are on the location. There are
a number of welcome provides for Africa too. As you will
soon read, thereare other welcome gives accessible for residents of other international locations To search out out more about
their impressive welcome provide, go to our Bet365 Bonus page .

Our special promo code is on the market for all of these offers.
The bonus code STYVIP1 can be utilized throughout registration, but does not change
the provide amount in any means. This means you can take an quantity when your group is successful or restrict your losses on all your dwell bets.

Most of the gathering at PureWin are indeed slots. These include 90K Yeti, King
Kong Cashpots, Diwali Dhamaka and Jammin’ Jars 2.

Notable jackpot slots include Microgaming’s
Mega Moolah series and NetEnt’s Divine Fortune. Whereas this
isn’t the world’s finest license to have, it remains to be a revered one.
PureWin Casino is, for the most part, one of the best
Indian casinos you will come throughout. Play on line casino video games from the most effective providers!
So enroll today at PureWin Casino and claim the very best bonus!
The Indian on line casino can also be dwelling to a weekly deposit bonus.
It additionally provides weekly reload bonuses for gamers who want to bolster their
steadiness. There are different promos and bonuses you may look at, too.

Minimum Deposit Limit: Each bonuses require a minimal deposit of ₹1,000.
It is value noting that with NetBanking, the minimum
deposit restrict is always ₹500.

If you are a veteran bettor or a novice in the field, 4Rabet India has a plethora of choices so that you can spend
your entertainment slot throughout your day. You may withdraw a minimum amount
of a thousand and a most amount of 1,00,000 utilizing the 4Rabet India On line casino
webpage. 4Rabet India was established in 2018. The casino is
licensed underneath the Curacao legal guidelines. Whichever method you select to deposit with,
the funds will reflect immediately in your casino account.
3. The accessible leagues/tournaments and matches on your chosen sport will then appear earlier than you.
2. Select the sport you want to guess for. The percentages of betting on each sport
are listed right before you once you choose the sport you want to guess on. Step 5: You'll
find the sports that you just frequently wager on and begin betting.
You may also watch live streaming of fashionable
sports through the website.

Every state that approves legislation to legalize online and retail sports activities betting is another potential marketplace for bet365.
Speed - The app might be the quickest to load and quickest whereas navigating by different games within the US market.
Whereas there isn’t a lot information about future
plans from bet365 in the US market, the sky is the
restrict for this international juggernaut. There would not be enough room
on this web page to checklist all of the obtainable betting options on bet365, however to offer just a little style of how large their choice is,
the above image is simply the pregame props part of Sport 1 of the World Sequence.
The sheer quantity of bets you can make is unmatched and include all the usual bets and a ton of props and reside in-game betting options.

10 deposit required. Free Bets added to Free Bet Credit steadiness.

Where a wager has been partially Cashed Out, only the remaining energetic risk will
depend.

Online casino and sports activities betting site 24Betting is a favourite Indian betting site.
It’s doable to enhance - a bigger software library and devoted Indian support would be a
very good begin. It isn't possible to find an ".in" on line casino or sportsbook that caters solely to Indian gamblers.
Nonetheless, 24Betting has ensured Indian bettors of its fairness, security, and legality.

Indian rupees are routinely displayed for all bets.
Responsible gambling insurance policies are in place, along with enforcement
instruments. 24-Betting is licensed and regulated by Costa Rica’s
Playing Authority. There isn't any lack of intent on the part of 24Betting, nevertheless, as
this is solely the result of having a Costa Rican license.
Nevertheless, it isn't all sunshine and roses. When you wish
to withdraw a big quantity in a single transaction, chances are you'll
accomplish that with none cap. Though there are limits - of sorts - for every cost methodology, every
has a cap for deposits, for instance.