Posts tagged with nginx:

SSL/Nginx/Django

I wanted to create a client portal of sorts to allow my clients to login and check billing status/history etc.  Since I pre-dominantly program websites in Django that part was a no brainer. But what was troubling me was dealing with the SSL and non-SSL parts.  I had only ever created "secure sites" in the past where everything was behind a login and run over SSL.  It was the flipping back and forth between secure and non that had me a little puzzled on how to implement.

I did some reading and eventually settled (for now) on using nginx (which I use as my main webserver) to look at the paths and redirect as needed:

if ($uri ~ (/bromin|/accounts|/invoices|/sf)) {
    rewrite (.*) https://nomad.ca$1 permanent;
}

So I have one of these blocks in the standard port 80 definition and another in the secure socket definition (with the operator switched to !~ and the rewrite to http).

The only reason I don't like this implementation is that the links in the HTML are not updated. So a link may claim it will take you to a secure page but might redirect to a non-secure page if the SSL isn't needed.  This violates a bit of what I would consider safe coding practice as a prudent user would notice the difference and it may raise suspicion.  However since I haven't even purchased a signed certificate this will do for now.

Default VHost in Nginx

I recently started using nginx as my main web server.  While it's a little tricky at first to figure out (documentation is all Russian), there are a few wiki's that help a lot.  One of the things I couldn't figure out was how it determines the "default" vhost.  In Apache this is the first host found in the Vhost configs (or alphabetically in sites-enabled/*) however this didn't seem to be the case with Nginx.

To make matters worse the way Nginx determines where to send traffic is significantly different than say Apache so some very weird things were happening with a couple of my hosts.  So after a bit of reading I found the missing link.   Logically enough it's the word default, the where is the weird part:

When defining a vhost it looks something like this:

server {
    listen 80;
    server_name server1.example.com;
    location / {
        root /path/to/server1.example.com/web/;
        expires 1d;
    }

To make this the default put "default" on the listen directive:

server {
    listen 80 default;
    server_name server1.example.com;
    location / {
        root /path/to/server1.example.com/web/;
        expires 1d;
    }

No more guessing or leaving it to nginx to determine the host based on URI.