daemon off;
user www-data www-data;

events {
    worker_connections  1024;
}

http {
    include mime.types;
    sendfile on;
    tcp_nopush on;

    client_max_body_size 100M;

    server {
        listen   80;
        root /application;
        index index.php index.html index.htm;
        server_name glitchcity.info www.glitchcity.info;
        location / {
            try_files $uri $uri/ /index.html;
        }

        error_page 404 /application/errors/404.html;
        error_page 500 502 503 504 /application/errors/50x.html;

        location = /50x.html {
            root /usr/share/nginx/www;
        }

        location = / {
            return 302 $scheme://$host/wiki/;
        }

        location = /wiki {
            return 302 $scheme://$host/wiki/;
        }

        location = /wiki/index.php {
            return 302 $scheme://$host/wiki/;
        }

        location ~ ^\/wiki/index.php/(.*)$ {
            return 302 $scheme://$host/wiki/$1;
        }

        location ~ ^\/wiki/.*$ {
            rewrite ^/wiki/(.*)$ /w/index.php?title=$1 last;
        }

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;

            # https://stackoverflow.com/a/36451158
            set $realip $remote_addr;
            if ($http_x_forwarded_for ~ "^(\d+\.\d+\.\d+\.\d+)") {
              set $realip $1;
            }
            fastcgi_param REMOTE_ADDR $realip;
        }
    }

    server {
        listen   80;
        root /application/forums;
        index index.php index.html index.htm;
        server_name forums.glitchcity.info;

        location / {
            try_files $uri $uri/ /index.html;
        }

        location ~ ^\/index.php/topic,(.*)$ {
            return 302 $scheme://$host/index.php?topic=$1;
        }

        error_page 404 /application/errors/404.html;
        error_page 500 502 503 504 /application/errors/50x.html;

        location = /50x.html {
            root /usr/share/nginx/www;
        }

        location ~ \.php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;

            set $realip $remote_addr;
            if ($http_x_forwarded_for ~ "^(\d+\.\d+\.\d+\.\d+)") {
              set $realip $1;
            }
            fastcgi_param REMOTE_ADDR $realip;
        }
    }
}
