Introduction
Are you a geek, a maker, a technician or a developer? Are you sometimes very proud of what you have created? Your own "baby" that does something great in its own way?
Well, we at ungleich are a team of DevOps, sysadmin and developers and today we want to share the gems of our current nginx configuration with you.
The Setup
The configuration we show you here is used for our Django based pages, on which we are running for instance rails-hosting.ch. Our Django application consists of various apps like blog, hosting or digitalglarus, which are all accessible on every domain. However, depending on which domain you access, you are given a different entrance page or redirect.
Let's see what we gems are in our configuration...
Gem #1: Handling / vs everything else
If you ever wondered what is the easiest way to do something for the entry page and something else for the rest of the page, here is an easy answer: Use location = / and location /: The = / block matches only, if the request is /, whereas the second location / matches everything else starting with a /.
location = / { Do something for / only }
location / { Do something for the rest }
For more information about how this works, have a look at the nginx location documentation.
Gem #2: Proxying / without a redirect to a Django app
We want our user to stay on the root of a specific domain (like django-hosting.ch in our case), when she requests /, but redirect her to django-hosting.ungleich.ch for every other request. We have multiple motivations to treat our users like this:
- If you go to example.com and do not click, it looks nice to have only example.com in the address bar
- Google adwords does not function with a cross domain redirect
- We want to support SSL, where possible. We have a wildcard SSL certificate for *.ungleich.ch that we want to use and not to manage SSL certificates for every vanity domain that we use
Given the previous distinction of treating / and non / differently, we can easily implement this behaviour by using the following code:
location = / {
rewrite ^/$ /$landingpagerewrite/ break;
uwsgi_pass uwsgiapp;
}
location / {
rewrite ^/(.*) https://$ungleich_servername/$1 permanent;
}
Gem #3: Only stay on / for some domains
Our original motivation to stay on the domain was because of reason #2 (the adwords problematic), but we want this only to happen for a few vanity domains that we use and not for every domain (indeed, most of our domains are redirecting to a sub url).
Even though the if directive of nginx should usually be avoided, it has a good use case: For testing the definition of variables. We setup the variable $landingpagerewrite, only in the case we want to stay on /. And this is how it looks like:
location = / {
if ($landingpagerewrite) {
rewrite ^/$ /$landingpagerewrite/ break;
}
}
More gems
There are many more gems that we would like to show you soon - stay tuned! If you have questions, do not hesitate to ask on Twitter!