include /etc/nginx/modules/*.conf;

worker_processes auto;
error_log stderr warn;
pid /run/nginx.pid;

events {
    worker_connections 1024;
}

http {
    include mime.types;
    default_type application/octet-stream;

    # Define custom log format to include reponse times
    log_format main_timed '$remote_addr - $remote_user [$time_local] "$request" '
                          '$status $body_bytes_sent "$http_referer" '
                          '"$http_user_agent" "$http_x_forwarded_for" '
                          '$request_time $upstream_response_time $pipe $upstream_cache_status';

    access_log /dev/stdout main_timed;
    error_log /dev/stderr notice;

	# client_body_timeout 12;
    # client_header_timeout 12;
    # keepalive_timeout 15;
    # send_timeout 10;

    # Max body size
    client_max_body_size 192M;
    client_body_buffer_size 10K;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 4k;

    # Write temporary files to /tmp so they can be created as a non-privileged user
    client_body_temp_path /tmp/client_temp;
    proxy_temp_path /tmp/proxy_temp_path;
    fastcgi_temp_path /tmp/fastcgi_temp;
    uwsgi_temp_path /tmp/uwsgi_temp;
    scgi_temp_path /tmp/scgi_temp;

    fastcgi_cache_path /tmp/fastcgi_proxy_cache levels=1:2 keys_zone=drupal:100m inactive=60m;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";

    server_tokens off;

    fastcgi_hide_header 'X-Drupal-Cache';
    fastcgi_hide_header 'X-Generator';
    fastcgi_hide_header 'X-Drupal-Dynamic-Cache';

    # Default server definition
    # More Info: https://www.nginx.com/resources/wiki/start/topics/recipes/drupal/
    server {
        listen [::]:8080 default_server;
        listen 8080 default_server;
        server_name _;

        sendfile off;

        root /opt/drupal/web;
        index index.php index.html;
        
        # Dont cache by default
        set $skip_cache 1;
        #  Do cache uris containing the following segments
        if ($request_uri ~* "/api/v1/") {
            set $skip_cache 0;
        }

        location = /favicon.ico {
            log_not_found off;
            access_log off;
        }

        location = /robots.txt {
            allow all;
            log_not_found off;
            access_log off;
        }

        location ~ \..*/.*\.php$ {
            return 403;
        }

        location ~ ^/sites/.*/private/ {
            return 403;
        }

        # Block access to scripts in site files directory
        location ~ ^/sites/[^/]+/files/.*\.php$ {
            deny all;
        }

        # Allow "Well-Known URIs" as per RFC 5785
        location ~* ^/.well-known/ {
            allow all;
        }

        # Block access to "hidden" files and directories whose names begin with a
        # period. This includes directories used by version control systems such
        # as Subversion or Git to store control files.
        location ~ (^|/)\. {
            return 403;
        }

        location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to index.php
            try_files $uri $uri/ /index.php?$args;
        }

        location @rewrite {
            rewrite ^ /index.php; 
        }

        # Don't allow direct access to PHP files in the vendor directory.
        location ~ /vendor/.*\.php$ {
            deny all;
            return 404;
        }

        # Protect files and directories from prying eyes.
        location ~* \.(engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?|xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|^(\.(?!well-known).*|Entries.*|Repository|Root|Tag|Template|composer\.(json|lock)|web\.config)$|^#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$ {
            deny all;
            return 404;
        }

        # Pass the PHP scripts to PHP-FPM listening on 127.0.0.1:9000
        location ~ '\.php$|^/update.php' {
            try_files $uri =404;

            fastcgi_buffers 16 16k; 
            fastcgi_buffer_size 32k;

            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param HTTP_PROXY "";
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param SCRIPT_NAME $fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_path_info;
            fastcgi_param QUERY_STRING $query_string;
            fastcgi_index index.php;
            fastcgi_intercept_errors on;
            include fastcgi_params;
            
            fastcgi_cache drupal;
            fastcgi_cache_valid 200 15s;

            add_header X-NCache $upstream_cache_status;

            fastcgi_ignore_headers Cache-Control Expires Set-Cookie Vary;
            fastcgi_hide_header Expires;
            fastcgi_cache_bypass $http_secret_header $skip_cache;
            fastcgi_no_cache $skip_cache;

            if ($request_uri ~* "/api/v1/") {
                more_set_headers 'Cache-Control: max-age=15s';
            }
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
            try_files $uri @rewrite;
            expires max;
            log_not_found off;
            access_log off;
        }

        location ~* \.(css|js|ico)$ {
            expires 1d;
        }

        location ~ ^/sites/.*/files/styles/ { 
            try_files $uri @rewrite;
        }

        location ~ ^/s3/files/styles/ {
            try_files $uri @rewrite;
        }

        # Handle private files through Drupal. Private file's path can come
        # with a language prefix.
        location ~ ^(/[a-z\-]+)?/system/files/ { # For Drupal >= 7
            try_files $uri /index.php?$query_string;
        }

        # Enforce clean URLs
        # Removes index.php from urls like www.example.com/index.php/my-page --> www.example.com/my-page
        # Could be done with 301 for permanent or other redirect codes.
        if ($request_uri ~* "^(.*/)index\.php/(.*)") {
            return 307 $1$2;
        }

        # Allow fpm ping and status from localhost
        location ~ ^/(fpm-status|fpm-ping)$ {
            access_log off;
            allow 127.0.0.1;
            deny all;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
        }

        # Redirect server error pages to the static page /50x.html
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /var/lib/nginx/html;
        }
    }
    
    gzip on;
    gzip_comp_level  2;
    gzip_min_length 10240;
    gzip_proxied any;
    gzip_types 
        text/plain
        text/css
        text/js
        text/xml
        text/html
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/xml+rss
        application/rss+xml
        image/svg+xml/javascript;
    gzip_vary on;
    gzip_disable "msie6";
    
    # Include other server configs
    include /etc/nginx/conf.d/*.conf;
}
