nginx


     сначала установим php

# server 
apt-get install -y nginx 

Настраиваем сервер certbot + php7.3

 


# перенос сайтов на другой домен
grep -rl ctapvk.ru . | xargs sed -i 's/ctapvk\.ru/buy-ali\.ru/g'
# отключить ssl
sed -i -r 's/(listen .*443)/\1;#/g; s/(ssl_(certificate|certificate_key|trusted_certificate) )/#;#\1/g' /etc/nginx/sites-enabled/*.conf
nginx -s reload
# включить ssl
sed -i -r 's/#?;#//g' /etc/nginx/sites-enabled/*.conf
nginx -s reload

На что обратитть внимаение при просмотре конфига

# open_basedir чтоб работало с deployer
fastcgi_param PHP_ADMIN_VALUE	"open_basedir=$base/:/usr/lib/php/:/tmp/:/home/ubuntu/work/";
nginx -t
systemctl reload nginx

сравнение апача и nginx

 У nginx асинхронная неблокирующая архитектура и нужно избегать тяжелых процессов в обработчиках запросов (именно поэтому, к примеру, в nginx нет классического cgi-интерфейса, только fcgi и uwsgi),

старый добрый Apache Httpd вместо nginx. Ключевые причины — богатый API и быстрая + дуракоустойчивая система пулов памяти. Если основная доля работы выполняется пользовательским кодом — асинхронный ввод-вывод nginx вдруг перестаёт приносить существенный прирост производительности. Ещё один важный момент — падение одного воркера апача от какого-нибудь неизбежного в С++ SIGSEGV создаёт меньше проблем, чем падение nginx.

 


Ускоряем Nginx за 5 минут

# This number should be, at maximum, the number of CPU cores on your system. 
worker_processes 24;

# Number of file descriptors used for Nginx.
worker_rlimit_nofile 200000;

# Only log critical errors.
error_log /var/log/nginx/error.log crit

events {

    # Determines how many clients will be served by each worker process.
    worker_connections 4000;

    # The effective method, used on Linux 2.6+, optmized to serve many clients with each thread.
    use epoll;

    # Accept as many connections as possible, after nginx gets notification about a new connection.
    multi_accept on;

}

http {

    # Caches information about open FDs, freqently accessed files.
    open_file_cache max=200000 inactive=20s; 
    open_file_cache_valid 30s; 
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    # Disable access log altogether.
    access_log off;

    # Sendfile copies data between one FD and other from within the kernel.
    sendfile on; 

    # Causes nginx to attempt to send its HTTP response head in one packet,  instead of using partial frames.
    tcp_nopush on;

    # Don't buffer data-sends (disable Nagle algorithm).
    tcp_nodelay on; 

    # Timeout for keep-alive connections. Server will close connections after this time.
    keepalive_timeout 30;

    # Number of requests a client can make over the keep-alive connection.
    keepalive_requests 1000;

    # Allow the server to close the connection after a client stops responding. 
    reset_timedout_connection on;

    # Send the client a "request timed out" if the body is not loaded by this time.
    client_body_timeout 10;

    # If the client stops reading data, free up the stale client connection after this much time.
    send_timeout 2;

    # Compression.
    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/xml;
    gzip_disable "msie6";


	# load configs
	include /etc/nginx/conf.d/*.conf;
	include /etc/nginx/sites-enabled/*;


}

 

A similar configuration for nginx would use fastcgi_param and would look somewhat like this:

location ~ ^/index\.php(/|$) {
    fastcgi_pass unix:/var/run/php7.1-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;

    fastcgi_param APP_ENV prod;
    fastcgi_param APP_DEBUG 0;
    fastcgi_read_timeout 300; # 

}
# conf 
cat << EOT >> /etc/nginx/sites-available/blog
server {
    listen 80 default_server;

    root /var/www/blog;
    index index.php index.html index.htm index.nginx-debian.html;

    server_name blog;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
    }

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

# create simlink
ln -s /etc/nginx/sites-available/blog /etc/nginx/sites-enabled/blog

 

 

 


 NGINX  reverse proxy

http://nginx.org/ru/docs/beginners_guide.html

server { # прокси слушает 8001 проксирует в 8000
    listen 8001 ssl; 
    client_max_body_size 100M;
    ssl_protocols       TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    # SSL
    ssl_certificate /etc/letsencrypt/live/remote.ctapvk.ru/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/remote.ctapvk.ru/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/remote.ctapvk.ru/chain.pem;
    location / {
        proxy_set_header   X-Real-IP   $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   Host $http_host;
        proxy_set_header   X-Forwarded-Proto $scheme;
        proxy_redirect   off;
        proxy_read_timeout  300;
        proxy_pass    http://127.0.0.1:8000;
        proxy_set_header Origin '*';
    }
}

 

 

 

Редиректы 

server {

  listen 80; 

  server_name www.buy-ali.ru;
  rewrite ^(.*) http://buy-ali.ru$1 permanent;
}

server {
    listen *:443;

    server_name buy-ali.ru;

    location / {
        return 301 http://buy-ali.ru$request_uri;
    }
}


#    if ($host ~* ^((.*).buy-ali.ru)$) {
#        set $subdomain $1;
#    }

#    if ($subdomain = "moderation") {
#	rewrite https://buy-ali.ru/moderator /$1 break;
#    }

#    location ~ ^/(.*) {
#   	rewrite https://buy-ali.ru/moderator /$1 break;
#		proxy_pass https://buy-ali.ru/moderator/$1;
#    }

HTTP basic authentication      

apt install -y apache2-utils
htpasswd -c /etc/nginx/.htpasswd
# добавить с паролем
htpasswd -b  /etc/nginx/.htpasswd user1 PASS_HERE
# удалить
htpasswd  -D  /etc/nginx/.htpasswd user1

Значения: Require (user Имя Имя : Имя | group Группа Группа : Группа | valid-user
Эта директива определяет принцип аутентификации:
User - только пользователи, указанные следующими через пробел, и указавшие верный пароль, смогут войти

server {
    ...
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    ...
}

не проверил

server {
    listen 80;
    root  /var/www/camera1/;
    location  /secret_hash {
        try_files $uri $uri/ =404; 
        autoindex on;
        autoindex_exact_size off;
        autoindex_format html;
        autoindex_localtime on;
    }
}

 

For ws

server {
	listen 3334 ssl http2 default_server;
    
	server_name domain.ru;
	# SSL
	ssl_certificate /etc/letsencrypt/live/domain.ru/fullchain.pem;
	ssl_certificate_key /etc/letsencrypt/live/domain.ru/privkey.pem;
	ssl_trusted_certificate /etc/letsencrypt/live/domain.ru/chain.pem;
    location / {
   		proxy_http_version 1.1;
   		proxy_set_header Upgrade $http_upgrade;
   		proxy_set_header Connection "upgrade";
        proxy_pass    http://127.0.0.1:3333;
    }
}

Отключение роботов через nginx

location = /robots.txt {
   add_header Content-Type text/plain;
   return 200 "User-agent: *\nDisallow: /\n";
}

 

NO cache for SPA

location = / {
    add_header Cache-Control no-cache;
    expires 0;
    try_files /index.html =404;
}

location / {
    gzip_static on;
    try_files $uri @index;
}

location @index {
    add_header Cache-Control no-cache;
    expires 0;
    try_files /index.html =404;
}

 

Multi lang SPA

server {
    listen 80;
    server_name test.local;
    #
    access_log off;

    root /var/www/test/;
    location / {
        try_files $uri $uri/index.html /ru$uri/index.html =404;
    }
}

 

Google verification

# simple not file 
location = /google9ac5185e9a426d.html {
  rewrite ^/(.*) $1;
  return 200 "google-site-verification: $uri";
}
if ($uri ~ "^(.*)/(google9ac5185e9a426d)(.*)"){
  set $mobile_rewrite perform;
}


# Unsure why alias didn't work, but this works for me:
location ~* /google.+\.html$ {
  try_files $uri =404;
}