настройка Nginx, php-fpm и virtualhost (Нужна помощь в настройке virtualhost)

Обсуждение настройки и работы сервисов, резервирования, сетевых настроек и вопросов безопасности ОС.

Модераторы: SLEDopit, Модераторы разделов

Аватара пользователя
viktor6
Сообщения: 87
ОС: Debian

настройка Nginx, php-fpm и virtualhost

Сообщение viktor6 »

Уважаемые гуру нужна ваша помощь в настройке виртуалхостов
Настраивал Nginx по этому мануалу http://howitmake.ru/blog/debian/62.html
Имеется много вирталхостов и не знаю как их настраивать
в апаче было так

Код: Выделить всё

<VirtualHost *:80>
   ServerName default
</VirtualHost>

<VirtualHost *:80>
    ServerName cs.datasvit.ks.ua
    ServerAlias www.cs.datasvit.ks.ua
    ServerAdmin v6@ukr.net
    DocumentRoot /home/www/site
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/Strike1-error.log
    CustomLog /home/www/logs/Strike1-access.log combined
</VirtualHost>

<VirtualHost *:80>
ServerName forum.cs.datasvit.ks.ua
    ServerAlias www.forum.cs.datasvit.ks.ua
    ServerAdmin v6@ukr.net
DocumentRoot /home/www/Strike/forum
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/forum1-Strike-error.log
    CustomLog /home/www/logs/forum1-Strike-access.log combined
</VirtualHost>

<VirtualHost *:80>
ServerName demo.cs.datasvit.ks.ua
    ServerAlias www.demo.cs.datasvit.ks.ua
    ServerAdmin v@ukr.net
DocumentRoot /home/www/Demo
    Options FollowSymLinks +Includes
</VirtualHost>

<VirtualHost *:80>
ServerName ggstat.cs.datasvit.ks.ua
    ServerAlias www.ggstat.cs.datasvit.ks.ua
    ServerAdmin v@ukr.net
DocumentRoot /home/www/test/ggstat
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/ggstat1-error.log
    CustomLog /home/www/logs/ggstat1-access.log combined
</VirtualHost>

<VirtualHost *:80>
ServerName monitor.cs.datasvit.ks.ua
    ServerAlias www.monitor.cs.datasvit.ks.ua
    ServerAdmin v6@ukr.net
DocumentRoot /home/www/Strike/monitoring
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/monitor1-error.log
    CustomLog /home/www/logs/monitor1-access.log combined
</VirtualHost>

<VirtualHost *:80>
ServerName ban.cs.datasvit.ks.ua
    ServerAlias www.bans.cs.datasvit.ks.ua
    ServerAdmin v6@ukr.net
DocumentRoot /home/www/Strike/bans
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/ban1-error.log
    CustomLog /home/www/logs/ban1-access.log combined
</VirtualHost>


<VirtualHost *:80>
ServerName stats.cs.datasvit.ks.ua
    ServerAlias www.Plusnet.cs.datasvit.ks.ua
    ServerAdmin v6@ukr.net
DocumentRoot /home/www/Strike/stats
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/stats1-error.log
    CustomLog /home/www/logs/stats1-access.log combined
</VirtualHost>

<VirtualHost *:80>
ServerName stats.data.cs.datasvit.ks.ua
    ServerAlias www.Datasvit.cs.datasvit.ks.ua
    ServerAdmin v6@ukr.net
DocumentRoot /home/www/Strike/stats2
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/stats.data1-error.log
    CustomLog /home/www/logs/stats.data1-access.log combined
</VirtualHost>

<VirtualHost *:80>
ServerName gungame.data.cs.datasvit.ks.ua
    ServerAlias www.GunGame.cs.datasvit.ks.ua
    ServerAdmin v6@ukr.net
DocumentRoot /home/www/Strike/gungame
    Options FollowSymLinks +Includes
    ErrorLog /home/www/logs/stats.data1-error.log
    CustomLog /home/www/logs/stats.data1-access.log combined
</VirtualHost>

<VirtualHost *:80>
DocumentRoot /home/viktor/KS_servera/Myac/logs
ServerName myac.cs.datasvit.ks.ua
<Directory /home/viktor/KS_servera/Myac/logs>
allow from all
Options +Indexes
</Directory>
</VirtualHost>
Спасибо сказали:
Аватара пользователя
Bizdelnick
Модератор
Сообщения: 21521
Статус: nulla salus bello
ОС: Debian GNU/Linux

Re: настройка Nginx, php-fpm и virtualhost

Сообщение Bizdelnick »

Пишите правильно:
в консоли
вку́пе (с чем-либо)
в общем
вообще
в течение (часа)
новичок
нюанс
по умолчанию
приемлемо
проблема
пробовать
трафик
Спасибо сказали:
Аватара пользователя
Olden Gremlin
Сообщения: 365
Статус: RAP22-RIPE
ОС: Debian GNU/Linux Wheezy

Re: настройка Nginx, php-fpm и virtualhost

Сообщение Olden Gremlin »

viktor6 писал(а):
23.11.2012 17:45
Уважаемые гуру нужна ваша помощь в настройке виртуалхостов
Настраивал Nginx по этому мануалу http://howitmake.ru/blog/debian/62.html
Имеется много вирталхостов и не знаю как их настраивать
Примеры ушли по скайпу ;)

Тут немного нарисую, что да к чему. По всем опциям великолепное описание можно и нужно читать тут - nginx: документация.
Далее сжато, конфигурация.
Далее, так сказать, основной конфиг.

Код: Выделить всё

$ egrep "^[ \t]*[a-z}{]" /etc/nginx.conf
user                            www-data        www-data;
worker_processes                1;
error_log                       /var/log/nginx/error.log;
pid                             /var/run/nginx.pid;
events {
    worker_connections          1024;
}
http {
    include                     /etc/nginx/mime.types;
    default_type                application/octet-stream;
    log_format main             '$remote_addr - $remote_user [$time_local] $host $request "$status" $body_bytes_sent "$http_referer" '
    access_log                  /var/log/nginx/access.log;
    reset_timedout_connection   on;
    gzip                        on;
    gzip_min_length             1300;
    gzip_buffers                8       32k;
    gzip_types                  text/plain text/css
    gzip_proxied                any;
    gzip_comp_level             5;
    gzip_disable                "msie6";
    gzip_vary                   on;
    open_file_cache             max=1000  inactive=20s;
    open_file_cache_valid       30s;
    open_file_cache_min_uses    2;
    open_file_cache_errors      on;
    server_name_in_redirect     off;
    client_max_body_size        512M;
    client_body_buffer_size     128k;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

include /etc/nginx/conf.d/*.conf и /etc/nginx/sites-enabled/* говорят о том, что из этих директорий, по указанной маске, необходимо подтянуть ещё конфигурацию. Условно разделено на две части, первая для каких-нибудь общих определений, которые не вошли в тело основного файла конфигурации, вторая для конфигурации каждого отдельно взятого виртуального хоста (собственно то о чём ты спрашиваешь).

Код: Выделить всё

find /etc/nginx/conf.d/*.conf -print -exec egrep "^[ \t]*[a-z}{]" {} ';'
[b]/etc/nginx/conf.d/common.conf[/b]
        proxy_buffering                 on;
        proxy_buffers                   512 8k;
        proxy_buffer_size               8k;
        proxy_read_timeout              180;
        proxy_connect_timeout           300;
        proxy_send_timeout              600;
        proxy_ignore_client_abort       off;
        proxy_intercept_errors          off;
        client_header_timeout           10m;
        client_body_timeout             10m;
        send_timeout                    10m;
        connection_pool_size            256;
        client_header_buffer_size       8k;
        large_client_header_buffers     100 8k;
        request_pool_size               4k;
        postpone_output                 1460;
        sendfile                        on;
        tcp_nopush                      on;
        tcp_nodelay                     on;
        keepalive_timeout               300 300;
        limit_req_log_level     notice;
        limit_conn_log_level    info;
[b]/etc/nginx/conf.d/geo.conf[/b]
geoip_country /usr/share/GeoIP/GeoIP.dat;
geo $geo {
    default UA;
}

Далее пример простенького хоста из /etc/nginx/sites-enabled/, назовём его sample.com:

Код: Выделить всё

server {
    listen 1.2.3.4:80;
    server_name sample.com www.sample.com;
    root /var/www/html/sample.com;
    include /etc/nginx/common/sample.com.conf;
}
upstream backend {
    server unix:/var/run/php5-fpm.sock;
}

/etc/nginx/common/sample.com.conf:

Код: Выделить всё

access_log /var/log/nginx/sample.com.access.log;
proxy_connect_timeout   75;
if ($loadavg_1m > 5)   { return 503; }
if ($loadavg_5m > 7)   { return 503; }
if ($loadavg_15m > 10) { return 503; }
location ~ /\.ht { deny  all; }
location ~* ^.+\.(bmp|jpg|jpeg|gif|ico|png|css|doc|txt|js|zip|iso|tgz|gz|rar|bz2|7z|xls|exe|pd
f|ppt|tar|wav|avi|rtf|mp3|mp4|mov|mpeg|mpg)$ {
    access_log          /var/log/nginx/sample.com.access-static.log;
    expires             5d;
    limit_rate          100M;
    if ($http_user_agent ~ FDM|Download) {
        limit_rate      50M;
    }
}
location ~ \.php$ {
    access_log  /var/log/nginx/sample.com-php.log;
    include     /etc/nginx/common/sample.com-fastcgi.conf;
    index       index.php;
    gzip        on;
    try_files   $uri    =404;
}
location / {
    access_log          /var/log/nginx/sample.com.access.log;
    index index.php;
    include /etc/nginx/common/sample.com-fastcgi.conf;
}
location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
}
location = /favicon.ico {
    log_not_found off;
    access_log off;
}

/etc/nginx/common/sample.com-fastcgi.conf:

Код: Выделить всё

    fastcgi_split_path_info ^(.+\.php)(.*)$;
    fastcgi_pass   backend;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /var/www/html/sample.com$fastcgi_script_name;
    include /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_intercept_errors        on;
    fastcgi_ignore_client_abort     off;
    fastcgi_connect_timeout 60;
    fastcgi_send_timeout 180;
    fastcgi_read_timeout 180;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 64 8k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;

В двух словах. Весь статический контент отдаётся непосредственно nginx-ом. Динамический контент (php) отдаётся php5-fpm.
/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;
fastcgi_param  REDIRECT_STATUS    200;


Безусловно, что в конфигурацию виртуального хоста можно добавить и другие украшалки и свистелки, но эта конфигурация достаточно минималистична и, если я ничего не пропустил, достаточна. ;)

К примеру, при большой нелюбви к китайцам можно сказать что-то наподобие

Код: Выделить всё

if ($geoip_country_code = CN) { return 444; }
if ($geoip_country_code = HK) { return 444; }

А скучное 404 поменять на "Сиськи не найдены!":

Код: Выделить всё

error_page 400 /400.html;
error_page 403 /403.html;
error_page 404 /404.html;
error_page 500 /500.html;
error_page 501 /501.html;
error_page 502 /502.html;
error_page 503 /503.html;
error_page 504 /504.html;
error_page 505 /505.html;
location ~ ^/(40[034]|50[012345])\.(html|jpg)$  {
    sub_filter  RELOADRESOURCE
                '<meta http-equiv=refresh content="7; url=$scheme://$host$request_uri">';
    sub_filter_once on;
    gzip        off;
    root /var/www/html/httperrors;
}

Можно закрыть доступ туда куда не следует лезть лишним любопытным глазкам:

Код: Выделить всё

location ~ /log { deny  all; }
location ~ /\.((svn|git)/|ht) { deny  all; }
location ~ \00 { deny all; }
«Когда у общества нет цветовой дифференциации штанов — то нет цели!»
nic-hdl: RAP22-RIPE
Спасибо сказали: