Install from package repository
sudo apt-get install nginx
Compiling and Installing From the Sources
sudo apt-get update -y && \
sudo apt-get install -y build-essential \
libpcre3 \
libpcre3-dev \
libpcrecpp0v5 \
libssl-dev \
zlib1g-dev
./configure --sbin-path=/usr/bin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--pid-path=/var/run/nginx.pid \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-debug \
--with-pcre \
--with-http_ssl_module
apt-get, то тогда автоматически настраивается linux service и создаётся init вскрипт. В таком случае можно запускать:
sudo /etc/init.d/nginx start
init скрипт не создан, то можно запустить
sudo nginx
sudo т.к. сервер должен прослушивать порт < 1000| Получение порта 80 | 443 |
sudo)/etc/nginx/nginx.conf - конфиг веб сервера
внутри конфига можно подключать другие конфиги
include /etc/nginx/site-enabled/*
все относительные пути в конфиге nginx являются относительно директории указанной как --prefix во время установки
/var/run/nginx.pid - id процесса nginx/var/log/nginx/error.log - лог ошибок/var/log/nginx/access.log - лог доступаscope, т.е. то к чему применяются конфиги gzip on;
# outer scope
access_log /var/logs/nginx/access.log main;
access_log /var/logs/nginx/notice.log notice;
# inner scope will override all array
access_log /var/logs/nginx/inner.log debug;
return 200;
try_files $uri /some/reserve/dir =404;
# user and group for workers
user www-data www-data;
# the amount of workers (by default 1, auto sets it to the number of CPUs)
worker_processes auto;
# error log location and level
error_log /var/log/nginx.error_log info;
events {
# the maximum connections per worker
worker_connections 1024;
# accept multiple connections simultaneously or only one connection at a time (the default is on)
multi_accept on;
}
# the begining of http server config
http {
# include file with mime types
include /etc/nginx/mime.types;
# defaut mime type
default_type application/octet-stream;
# the log format
log_format simple '$remote_addr $request $status';
# client timeouts
client_body_timeout 12;
client_header_timeout 12;
# Use a higher keepalive timeout to reduce the need for repeated handshakes
keepalive_timeout 300;
# server timeout
send_timeout 10;
# virtual server config
server {
# nginx port
listen 80;
# root directory for site
root /www/site;
location / {
root /www/site/index.html;
# adds some header to response
add_header "Cache-Control" "no-transform";
}
}
}
ulimit -n - gets linux core the restiction of maximum number of connections per CPU. It’s best practise to use it number as worker_connections value.location в порядке убывания
location = /img/1.jpg - точное совпадениеlocation ^~ /pic/ - префикс с приоритетом над регулярным выражениемlocation ~ \.jpg$, location ~* \.jpg$ - casesensetive caseinsensetive совпадение по регулярному выражениюlocation /img/ - совпадение по префиксуlocation имеют одинаковый приоритет, то применяется тот который расположен выше в конфиге.location путь можно указать несколькими способами
root - абсолютный url
location ~* ^.+\.(jpg|jpeg|gif)$ {
root /www/images
}
/2015/10/img.png -> /www/images/2015/10/img.pngalias - путь относительно префикса
location /sitemap/ {
alias /home/www/generated;
}
/sitemap/index.html -> /home/www/generated/index.html $ ps -o pid,euser,egroup,comm,args -C nginx
PID EUSER EGROUP COMMAND COMMAND
1 root root nginx nginx: master process nginx -g daemon off;
7 nginx nginx nginx nginx: worker process
$ ls -lah /home
drwxr-xr-x 3 root root 4,0K авг. 30 07:45 .
drwxr-xr-x 24 root root 4,0K авг. 29 08:38 ..
drwxr-xr-x 53 max max 4,0K авг. 30 09:59 max
drwxr-xr-x - права доступа
max (3 колонка) - обладатель файлаmax (4 колонка) - группа обладателя файлаlocation /node {
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://127.0.0.1:3000;
}
proxy_pass - проксирует запрос на указанный upstreamproxy_set_header - добавление\изменение заголовков HTTP сообщения
Host для предоставления нужного заголовка хост для бекенда.X-Real-IP - устанавливает заголовок IP для того чтобы знать с какого IP пришёл запрос (в противном случае всегда будем получать запросы с IP прокси сервера.)upstream backend {
least_conn;
server back1.example.com:8080 weight=1 max_fails-3;
server back2.example.com:8080 weight=2;
server backup1.example.com:8080 backup;
}
location / {
proxy_pass http://backend;
}
upstream - список серверов работающих под одним именем.ip_hash - если клиент был соединён с определённым сервером - продолжает его всегда туда направлять.least_conn - направляет к тому серверу с которым установленно наименьшее количество соединений.weight - вес сервера при распределении запросов (более мощным серверам ставят больший weight)max_fails - максимальное количество фейлов перед тем как сервер будет отключен location ~* \.(css|js|jpg|png|gif)$ {
expires 1M;
add_header Pragma public;
add_header Cache-Control public; # tell that every proxy could cache it
add_header Vary Accept-Encoding; # intermideate proxy should split resource cache by Accept-Encoding
}
gzip on;
gzip_min_length 100;
gzip_comp_level 3;
gzip_types text/plain;
gzip_types text/css;
gzip_types application/javascript;
gzip_disable "msie6"; # disable gzip for user agent Internet Exporer 6
sudo mkdir /etc/nginx/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
./configure --help | grep without
http_autoindex_module server_tokents off;
if ($http_user_agent ~* some_bot_pattern) {
return 403;
}