# configuration file /etc/nginx/nginx.conf:
user useriuss;
pid /var/run/nginx.pid;

worker_processes  auto; 
worker_rlimit_nofile 8192;

events {
	worker_connections  2048;
	use epoll;
	multi_accept on;
}

http {
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    server_tokens   off;

	error_log   /var/log/nginx/error.log error;
	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
	access_log off;

    keepalive_timeout  20;
	send_timeout 10;
    reset_timedout_connection on; 
	output_buffers   4 32k; 
	client_header_timeout 12;
	client_body_timeout 12;
	client_body_buffer_size  128k;
	client_header_buffer_size 3m;
	client_max_body_size        20m;
	large_client_header_buffers 4 256k;
	client_body_temp_path       /var/spool/nginx_client_body_temp;

    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
	charset UTF-8;	
	
    gzip            on;
    gzip_static     on;
	gzip_vary on;
    gzip_comp_level 4;
    gzip_min_length 1024;
	gzip_http_version 1.1;
	gzip_buffers 4 32k;
	gzip_types text/plain application/xml application/x-javascript text/css text/javascript image/svg+xml;

# cache informations about file descriptors, frequently accessed files
# can boost performance, but you need to test those values
	open_file_cache max=64000 inactive=40s;
	open_file_cache_valid 60s;
	open_file_cache_min_uses 2;
	open_file_cache_errors on;

### NGINX Simple DDoS Defense	
#	limit_conn_zone $binary_remote_addr zone=isp:10m;
#	limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;		

### Прокси
   proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
   proxy_set_header   Host              $host;
   proxy_set_header   X-Real-IP         $remote_addr;

   port_in_redirect   off;

   proxy_pass_header  Server;
   proxy_redirect     off;
   proxy_buffering    on;

   proxy_buffer_size      16k;
   proxy_buffers  8 128k;
   proxy_busy_buffers_size    256k;

   proxy_next_upstream         off;
   proxy_intercept_errors      off;
   proxy_connect_timeout       90;
   proxy_read_timeout          90;
   proxy_send_timeout          90;

   proxy_temp_file_write_size  256k;
   proxy_max_temp_file_size    0;

   proxy_temp_path             /var/spool/nginx_proxy_temp;

### Подключение других конфигов	
	include /etc/nginx/conf.d/*.conf;

server {
    listen      82;
	server_name site.ru www.site.ru localhost;
	
	location / {
		proxy_pass         http://127.0.0.1:81;
		proxy_redirect     http://www.site.ru:80/ /;
	}

	location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|bmp|rtf|flv|js|swf|mp3|ogg|flac|avi|mp4|gp|wma|wmv|wav)$ {
		root    /var/www/site;
		error_page 404 = @fallback;
		expires max;
	}

	location ~* (\.swf|\.js)$ {
		valid_referers none blocked server_names ~(site.ru|google.|yandex.|bing.);
		if ($invalid_referer) {return 403;}
	}

	location @fallback {
		proxy_pass http://127.0.0.1:81;
	}

    listen 443 ssl http2; # managed by Certbot
	ssl_certificate /etc/letsencrypt/live/site.ru/fullchain.pem; # managed by Certbot
	ssl_certificate_key /etc/letsencrypt/live/site.ru/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot	

} 

} 

# configuration file /etc/nginx/mime.types:

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/x-javascript              js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

application/font-sfnt            otf ttf;
application/font-woff            woff;
application/font-woff2           woff2;
application/vnd.ms-fontobject    eot;

    application/java-archive              jar war ear;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.ms-excel              xls;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
 #   application/octet-stream              eot;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

# configuration file /etc/nginx/conf.d/site.ru.conf:
fastcgi_cache_path /var/lib/nginx/fastcgi_cache/ levels=1:2 keys_zone=cache:100m inactive=1d max_size=1G;
fastcgi_temp_path /var/lib/nginx/fastcgi_temp/ 1 2;
fastcgi_ignore_headers "Cache-Control" "Expires" "Set-Cookie";
fastcgi_cache_min_uses 1;
fastcgi_cache_valid  200 302  10m;
fastcgi_cache_valid  404      1m;
fastcgi_cache_use_stale error timeout invalid_header http_500 http_503;
fastcgi_cache_key "$request_method|$host|$request_uri";
fastcgi_buffers 256 4k;
fastcgi_cache_lock              on;

server {
	listen      80;
	server_name site.ru localhost;
	return 301 https://$host$request_uri;
}

server {
	listen      81;
	listen      8080 default_server;
	server_name site.ru localhost;
	charset utf-8;
	rewrite_log off;
	access_log /var/log/nginx/site.ru.access.log main buffer=16k;
	autoindex off;

	root    /var/www/site;
	include conf.d/rewrites.inc;
	index index.php index.html;

	# Disallow iframe
	add_header X-Frame-Options "SAMEORIGIN";	

	include conf.d/common.inc;
	include conf.d/common-loc.inc;

# Ограничь количество доступных методов обращения к Web-серверу (секция server)
	if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; }

# Insert this in server configuration:
	if ($bad_referer) { return 444; }
# Insert this in server configuration:
	if ($bad_bot) { return 403; }

	location ~* ^.+\.(xml|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|pdf|txt|tar|bmp|rtf|flv|js|swf|mp3|avi|srt|mp4|gp|wav|eot|ttf|woff|woff2|svg)$ {
		expires max;
		access_log off; 
		log_not_found off;

# для файлов выше 1m ограничить скорость		
		limit_rate_after 2m; 
		limit_rate 250k;

# Отправить заголовки для кеширования браузером		
		add_header Pragma "public";
		add_header Cache-Control "public, must-revalidate, proxy-revalidate";
	}	
	
	location ~* \.html$ {
		expires modified 1200s;
		add_header Vary Cookie;
		add_header Pragma "public";
		add_header Cache-Control "max-age=1200, public, must-revalidate, proxy-revalidate";
	}
	
	location ~* (\.swf|\.js)$ {
		valid_referers none blocked server_names ~(google.|yandex.|bing.);
		if ($invalid_referer) {
			return 403;
		}
	}

   listen 443 ssl http2; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/site.ru/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/site.ru/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

	# Дополнительные параметры https://mozilla.github.io/server-side-tls/ssl-config-generator/?server=nginx-1.14.0&openssl=1.0.2k&hsts=yes&profile=intermediate
		#ssl_session_cache shared:SSL:30m; #вместо 1м по умолчанию
		ssl_session_tickets off; 
		ssl_buffer_size 8k;	 
		add_header Strict-Transport-Security max-age=15768000;	# HST 6 months
		
}

# страницы ошибок
error_page 404         /errors/404.html;
error_page 403         /errors/403.html;
error_page 500 502 504 /errors/50x.html;
error_page 503         /errors/503.html; # профилактические работы

# запретить исполнение php и др. в директориях с загруженными иллюстрациями
rewrite w/images/.*\.php /errors/404.html;
rewrite /wp-content/uploads/.*\.php /errors/404.html;
location /errors/ { internal; }

#####################
# Wordpress
# https://codex.wordpress.org/Nginx
#####################

 location / {
 	try_files $uri $uri/ /index.php?$args;
 }
 rewrite /wp-admin$ $scheme://$host$uri/ permanent;
 include conf.d/common-loc.inc; 
 
 #had simplified configuration

#####################
## SQL Injection and similar attacks
#####################
        location ~* "(eval\()"  { deny all; }
        location ~* "(127\.0\.0\.1)"  { deny all; }
        location ~* "([a-z0-9]{2000})"  { deny all; }
        location ~* "(javascript\:)(.*)(\;)"  { deny all; }
        location ~* "(base64_encode)(.*)(\()"  { deny all; }
        location ~* "(GLOBALS|REQUEST)(=|\[|%)"  { deny all; }
        location ~* "(<|%3C).*script.*(>|%3)" { deny all; }
        location ~ "(\\|\.\.\.|\.\./|~|`|<|>|\|)" { deny all; }
        location ~* "(boot\.ini|etc/passwd|self/environ)" { deny all; }
        location ~* "(thumbs?(_editor|open)?|tim(thumb)?)\.php" { deny all; }
        location ~* "(\'|\")(.*)(drop|insert|md5|select|union)" { deny all; }
        location ~* "(https?|ftp|php):/" { deny all; }
        location ~* "(=\\\'|=\\%27|/\\\'/?)\." { deny all; }
#       location ~* "/(\$(\&)?|\*|\"|\.|,|&|&amp;?)/?$" { deny all; }
        location ~ "(\{0\}|\(/\(|\.\.\.|\+\+\+|\\\"\\\")" { deny all; }
        location ~ "(~|`|<|>|;|%|\\|\s|\{|\}|\[|\]|\|)" { deny all; }
        location ~* "/(=|\$&|_mm|(wp-)?config\.|cgi-|etc/passwd|muieblack)" { deny all; }
        location ~* "(&pws=0|_vti_|\(null\)|\{\$itemURL\}|echo(.*)kae|etc/passwd|eval\(|self/environ)" { deny all; }
        location ~* "\.(aspx?|bash|bak?|cfg|cgi|dll|exe|git|hg|ini|jsp|log|mdb|out|sql|svn|swp|tar|rdf)$" { deny all; }
        location ~* "/(^$|mobiquo|phpinfo|shell|sqlpatch|thumb|thumb_editor|thumbopen|timthumb|webshell)\.php" { deny all; }

# configuration file /etc/nginx/fastcgi_params:

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

# configuration file /etc/nginx/conf.d/common-loc.inc:
location  ~ \.php$ {
	fastcgi_cache_bypass $skip_cache;
	fastcgi_no_cache $skip_cache;
	fastcgi_cache cache;
	fastcgi_cache_valid 30m;

	try_files $uri =404;
	fastcgi_pass 127.0.0.1:9000;
	fastcgi_index index.php;
	include fastcgi_params;
}

location ~ /\.passwd { deny  all; }
location ~ /\.ht { deny  all; }
location ~ /\.hg/ { deny  all; }
location ~ /\.svn/ { deny  all; }
location ~ /\.git/ { deny  all; }


# configuration file /etc/letsencrypt/options-ssl-nginx.conf:
# This file contains important security parameters. If you modify this file
# manually, Certbot will be unable to automatically provide future security
# updates. Instead, Certbot will print and log an error message with a path to
# the up-to-date file that you will need to refer to when manually updating
# this file.

ssl_session_cache shared:nginx_SSL:30m;
ssl_session_timeout 1440m;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

ssl_ciphers " "; #deleted


## Add here all user agents that are to be blocked.
map $http_user_agent $bad_bot {
    default 0;
    ~*^Lynx 0; # Let Lynx go through
    libwww-perl                      1;
    ~*(?i)(httrack|htmlparser|libwww|JikeSpider|proximic|Sosospider|Baiduspider|Sogou|YoudaoBot|DoCoMo|msnbot|BBBike|WWWOFFLE|Widow|SuperHTTP|BlackWidow|HTTrack|Java|Pixray|CPython|Spinn3r|Abonti|MSIECrawler|Baiduspider|Siteimprove|Aboundex|80legs|360Spider|^Java|Cogentbot|^Alexibot|^asterias|^attach|^BackDoorBot|^BackWeb|Bandit|^BatchFTP|^Bigfoot|^Black.Hole|^BlackWidow|^BlowFish|^BotALot|Buddy|^BuiltBotTough|^Bullseye|^BunnySlippers|^Cegbfeieh|^CheeseBot|^CherryPicker|^ChinaClaw|Collector|Copier|^CopyRightCheck|^cosmos|^Crescent|^Custo|^AIBOT|Mozilla/4.0|ZmEu|MJ12bot|MegaIndex|OpenLinkProfiler|spbot|^Snake|DLE_Spider|Apache-HttpClient|discobot|WordPress|BLEXBot|SolomonoBot|SetLinks|kmbot|Embedly|RadioClicker|VoilaBot) 1;
}

## Add here all referrers that are to blocked.
map $http_referer $bad_referer {
    default 0;
    ~(?i)(adult|babes|click|diamond|forsale|girl|jewelry|love|nudit|organic|poker|porn|poweroversoftware|sex|teen|webcam|zippo|casino|replica|en.savefrom.net|7makemoneyonline.com|acunetix-referrer.com|adcash.com|bithack.ru|buttons-for-website.com|cenokos.ru|cenoval.ru|cityadspix.com|darodar.com|econom.co|edakgfvwql.ru|gobongo.info|iedit.ilovevitaly.com|ilovevitaly.com|ilovevitaly.co|ilovevitaly.info|ilovevitaly.org|ilovevitaly.ru|iskalko.ru|luxup.ru|make-money-online.7makemoneyonline.com|maps.ilovevitaly.com|myftpupload.com|savefrom.net|savetubevideo.com|screentoolkit.com|semalt.com|seoexperimenty.ru|shopping.ilovevitaly.ru|slftsdybbg.ru|socialseet.ru|srecorder.com|st3.cwl.yahoo.com|superiends.org|vodkoved.ru|websocial.me|ykecwqlixx.ru|yougetsignal.com|priceg.com|responsinator.com|o-o-6-o-o.ru|o-o-8-o-o.ru) 1;
}

## Add here all hosts that should be spared any referrer checking.
geo $bad_referer {
    127.0.0.1 0;
    192.168.1.0/24 0;
    217.23.7.130 0;
    78.110.60.230 0;
    193.227.240.37 0;
	172.31.1.100 0;
	78.47.141.187 0;
    193.227.240.38 0;
}

# configuration file /etc/nginx/conf.d/default.conf:
server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}


# configuration file /etc/nginx/conf.d/status.conf:
server {
	listen 127.0.0.1:80;
	access_log   off;
	location /fpm_ping {
		fastcgi_pass 127.0.0.1:9000;
		include fastcgi_params;
	}
	location /fpm_status {
		fastcgi_pass 127.0.0.1:9000;
		include fastcgi_params;
	}
	location /nginx_status {
		stub_status on;
	}

}


