# you must set worker processes based on your CPU cores, nginx does not benefit from setting more than that
worker_processes auto; #some last versions calculate it automatically

# number of file descriptors used for nginx
# the limit for the maximum FDs on the server is usually set by the OS.
# if you don't set FD's then OS settings will be used which is by default 2000
worker_rlimit_nofile 4096;

error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

events {
    worker_connections  4096;
}

http {
    map $sent_http_content_type $expires {
        default                    off;
        text/html                  off;
        text/css                   off;
        application/javascript     off;
        application/font-woff2     4h;
        ~image/                    4h;
    }

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
    proxy_hide_header X-Powered-By;
    add_header X-Frame-Options DENY;
    add_header X-Content-Type-Options nosniff;
    add_header X-XSS-Protection "1; mode=block";

    #Strict Transport Security
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' ttps://www.google-analytics.com https://mc.yandex.ru; img-src 'self' https://www.google-analytics.com/ https://mc.yandex.ru/ data:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com/; font-src 'self' data: https://fonts.gstatic.com/; child-src 'self' https://www.google.com/maps/; connect-src 'self' wss://lab.lectrum.io/redux/ws/ https://www.google-analytics.com/ https://mc.yandex.ru/; object-src 'none' ";

    log_format '$remote_addr - $remote_user [$time_local] '
                           '"$request" $status $body_bytes_sent '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';

    server_tokens off;

    # cache informations about FDs, frequently accessed files
    # can boost performance, but you need to test those values
    open_file_cache max=200000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # copies data between one FD and other from within the kernel
    # faster then read() + write()
    sendfile on;

    # send headers in one peace, its better then sending them one by one
    tcp_nopush on;

    # don't buffer data sent, good for small data bursts in real time
    tcp_nodelay on;

    # reduce the data that needs to be sent over network -- for testing environment
    gzip on;
#    gzip_min_length 10240;
    gzip_proxied expired no-cache no-store private auth;
    gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/json application/xml;
    gzip_disable msie6;

    # allow the server to close connection on non responding client, this will free up memory
    reset_timedout_connection on;

    # request timed out -- default 60
    client_body_timeout 10;

    # if client stop responding, free up memory -- default 60
    send_timeout 2;

    # server will close connection after this time -- default 75
    keepalive_timeout 30;

    # Denys some IPS
    # deny xxx.xxx.xxx.xxx;

    # redirect to HTTPS
    # server {
    #     listen       80;
    #     listen       [::]:80;
    #     server_name  sotream.xyz;
    #     return 301 https://sotream.xyz$request_uri;
    # }

    upstream docker-registry {
        server registry:5000;
    }

    ## Set a variable to help us decide if we need to add the
    ## 'Docker-Distribution-Api-Version' header.
    ## The registry always sets this header.
    ## In the case of nginx performing auth, the header is unset
    ## since nginx is auth-ing before proxying.
    map $upstream_http_docker_distribution_api_version $docker_distribution_api_version {
        '' 'registry/2.0';
    }

    server {
        listen       443 ssl http2;
        listen       [::]:443 ssl http2;
        server_name  sotream.xyz;
        resolver 8.8.4.4 8.8.8.8 valid=300s;
        resolver_timeout 10s;

        ssl_stapling on;
        ssl_stapling_verify on;

        # Сгенерированные при помощи Lets Encrypt
        ssl_certificate /etc/ssl/certs/fullchain.pem;
        ssl_certificate_key /etc/ssl/certs/privkey.pem;
        ssl_trusted_certificate	/etc/ssl/certs/chain.pem;

        # Для самоподписанных
        # ssl_certificate /etc/nginx/ssl/nginx.crt;
        # ssl_certificate_key /etc/nginx/ssl/nginx.key;
        # ssl_dhparam /etc/nginx/ssl/dhparam.pem;

        # Set up preferred protocols and ciphers. TLS1.2 is required for HTTP/2
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!aNULL:!ADH:!AECDH:!MD5;

        # This is a cache for SSL connections
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 60m;

        # disable any limits to avoid HTTP 413 for large image uploads
        client_max_body_size 0;

        # required to avoid HTTP 411: see Issue #1486 (https://github.com/moby/moby/issues/1486)
        chunked_transfer_encoding on;

        access_log  off;

        if ( $http_user_agent ~* (nmap|nikto|wikto|sf|sqlmap|bsqlbf|w3af|acunetix|havij|appscan) ) {
            return 444;
        }

        # location / {
	    #     root /var/www/html;
        #     try_files $uri /index.html;
        # }

        # location /api {
        #     proxy_pass http://api:3000;
        #     proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        #     proxy_redirect  off;
        #     proxy_buffering off;
        #     proxy_set_header        Host               $host;
        #     proxy_set_header        X-Real-IP          $remote_addr;
        #     proxy_set_header        X-Forwarded-For    $proxy_add_x_forwarded_for;
        #     expires                 $expires;
        # }

        location /v2/ {

            # Do not allow connections from docker 1.5 and earlier
            # docker pre-1.6.0 did not properly set the user agent on ping, catch "Go *" user agents
            if ($http_user_agent ~ "^(docker\/1\.(3|4|5(?!\.[0-9]-dev))|Go ).*$" ) {
                return 404;
            }

            ## If $docker_distribution_api_version is empty, the header is not added.
            ## See the map directive above where this variable is defined.
            add_header 'Docker-Distribution-Api-Version' $docker_distribution_api_version always;

            proxy_pass http://docker-registry;
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            proxy_redirect  off;
            proxy_buffering off;
            proxy_set_header  Host              $http_host;   # required for docker client's sake
            proxy_set_header  X-Real-IP         $remote_addr; # pass on real client's IP
            proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
            proxy_set_header  X-Forwarded-Proto $scheme;
            proxy_read_timeout                  900;
            expires -1;
        }
    }
}