# Request limit zone to help mitigate attacks
limit_req_zone $binary_remote_addr zone=ip:10m rate=5r/s;

# Cleartext listener for LetsEncrypt and HTTPS redirects.
server {
    listen 80;

    server_name ponepaste.org;

    location ^~ /.well-known/acme-challenge/ {
        root /var/www/letsencrypt/;
    }

    location / {
        return 301 https://ponepaste.org$request_uri;
    }
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;

    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/ponepaste.org/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/ponepaste.org/privkey.pem;
    add_header Strict-Transport-Security "max-age=63072000" always;

    # ModSecurity config; optional, but recommended.
    modsecurity on;
    modsecurity_rules_file /etc/modsecurity/modsecurity.conf;

    root /srv/http/ponepaste.org;
    index index.html index.php;

    server_name ponepaste.org;

    # Rewrites for pretty URLs
    rewrite ^/([0-9]+) /paste.php?id=$1 last;
    rewrite ^/page/([a-zA-Z0-9]+)/? /pages.php?page=$1 last;
    rewrite ^/archive /archive.php last;
    rewrite ^/discover /discover.php last;
    rewrite ^/profile /profile.php last;
    rewrite ^/user/([^/]+)/?$ /user.php?user=$1 last;
    rewrite ^/user/([^/]+)/([^/]+)/?$ /user.php?user=$1&q=$2 last;
    rewrite ^/contact /contact.php last;
    rewrite ^/download/(.*)$  /paste.php?download&id=$1 last;
    rewrite ^/raw/(.*)$  /paste.php?raw&id=$1 last;
    rewrite ^/embed/(.*)$  /paste.php?embed&id=$1 last;
    rewrite ^/report  /report.php last;
    rewrite ^/event  /event.php last;
    rewrite ^/rules /rules.php last;

    location ~* \.(jpg|jpeg|png|gif|ico|css|js) {
      add_header "Cache-Control" "public";
      expires 1h;
    }

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        limit_req zone=ip burst=10 delay=8;
        include snippets/fastcgi-php.conf;

        fastcgi_pass unix:/run/php/php-fpm.sock;
    }

    # Deny directories that should not be publicly accessible.
    location ~ (/doc|/tmp|/includes|/config|/.git|/.ht|/js|/node_modules|/composer).* {
        deny all;
    }

    location ~ /\.ht {
        deny all;
    }
}
