Рубрики
Uncategorized

Конфигурация утилиты Nginx

Автор оригинала: David Wong.

1 противоугонная цепь

Связанная конфигурация:

действительные_референты

location ~* \.(gif|jpg|png)$ {
    #Only 192.168.0.1 requests are allowed
    valid_referers none blocked 192.168.0.1;
    if ($invalid_referer) {
       rewrite ^/ http://$host/logo.png;
    }
}

2 установите время истечения срока действия в соответствии с типом файла

location ~.*\.css$ {
    expires 1d;
    break;
}
location ~.*\.js$ {
    expires 1d;
    break;
}
location ~* \.(js|css|jpg|jpeg|gif|png)$ {
    expires 1h;
    break;
}

3 нет доступа к каталогу

location ~* \.(txt|doc)${
    root /opt/htdocs/site/test;
    deny all;
}

4 статический доступ к ресурсам

http {
    #This will specify the cache for the open file, which is not enabled by default. Max specifies the number of caches,
    #It is recommended to be consistent with the number of open files. Inactive refers to how long it takes for a file to be deleted after it has not been requested.
    open_file_cache max=204800 inactive=20s;

    #The minimum number of times the file is used within the time of the inactive parameter in the open file cache instruction,
    #If this number is exceeded, the file descriptor is always opened in the cache. For example, if there is one
    #If the file is not used once in inactive time, it will be removed.
    open_file_cache_min_uses 1;

    #This refers to how often to check the cached valid information
    open_file_cache_valid 30s;

    #By default, nginx's gzip compression is turned off. Gzip compression can save you no money
    #Less bandwidth, but it will increase the CPU cost of the server. Nginx only compresses text / HTML by default,
    #If we want to compress and transfer content other than HTML, we need to set it manually.
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;

    server {
        listen       80;
        server_name www.test.com;
        charset utf-8;
        root   /data/www.test.com;
        index  index.html index.htm;
    }
}

5 конфигурация журнала

5.1 описание поля журнала

Удаленное добавление и пересылка по HTTP для IP-адрес клиента
удаленный пользователь Имя пользователя клиента
запрос Запрошенный URI и протокол HTTP
статус Состояние запроса
body_bytes_sent Количество байтов, возвращаемых клиенту, без учета размера заголовка ответа
bytes_sent Общее количество байтов, возвращенных клиенту
соединение Серийный номер подключения
запросы на подключение Текущее количество запросов для одного и того же TCP-соединения
мсек Время записи в журнал. Единица измерения-секунда, точность-миллисекунда
труба Если запрос отправляется через HTTP-конвейер, значение канала равно “P”, в противном случае это “.”
http_referer Запись, с какой страницы ссылаются
http_user_agent Запись информации о браузере клиента
длина запроса Длина запроса (включая строку запроса, заголовок запроса и тело запроса)
time_iso8601 Местное время в стандартном формате iso 8601
временный_локальный Запись времени доступа и часового пояса

5.1 журнал доступа

http {
    log_format  access  '$remote_addr - $remote_user [$time_local] $host "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for" "$clientip"';
    access_log  /srv/log/nginx/talk-fun.access.log  access;
}

5.2 журнал ошибок

error_log  /srv/log/nginx/nginx_error.log  error;
#Error log / dev / null; true close error log
http {
    # ...
}

6 обратный агент

http {
    include mime.types;
    server_tokens off;

    ##Configure parameters for reverse proxy
    server {
        listen    8080;

        ##1. If the user visits http://ip: port, the reverse proxy will go to https://github.com
        location / {
            proxy_pass  https://github.com;
            proxy_redirect     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;
        }

        ##2. If the user accesses http://ip: port/readme.md, the reverse proxy will
        ##   https://github.com/zibinli/blog/blob/master/README.md
        location /README.md {
            proxy_set_header  X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass https://github.com/zibinli/blog/blob/master/README.md;
        }
    }
}

7 балансировка нагрузки

http {
    upstream test.net {
        ip_hash;
        server 192.168.10.13:80;
        server 192.168.10.14:80  down;
        server 192.168.10.15:8009  max_fails=3  fail_timeout=20s;
        server 192.168.10.16:8080;
    }
    server {
        location / {
            proxy_pass  http://test.net;
        }
    }
}