English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Подробное описание шагов для реализации лога доступа браузера в реальном времени с помощью Nginx

Первый раздел: сначала проверьте версию nginx, я использую версию 1.9.7, установленный каталог в /application/nginx-1.9.7

[root@AnSheng ~]# /application/nginx-1.9.7/sbin/nginx -V
версия nginx: nginx/1.9.7
собран с gcc 4.4.7 20120313 (Red Hat 4.4.7-16) (GCC)
аргументы configure: --prefix=/application/nginx-1.9.7 --user=nginx --group=nginx --with-http_stub_status_module

Второй раздел: проверьте грамматику и запустите nginx

[root@AnSheng ~]# /application/nginx-1.9.7/sbin/nginx -t
nginx: the configuration file /application/nginx-1.9.7/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.9.7/conf/nginx.conf test is successful
[root@AnSheng ~]# /application/nginx-1.9.7/sbin/nginx

Третий раздел: удалите из файла конфигурации nginx избыточные комментирующие строки и пустые строки

[root@AnSheng ~]# cd /application/nginx-1.9.7/conf/
[root@AnSheng conf]# egrep -v "#|^$" nginx.conf.default
worker_processes 1;
events {
 worker_connections 1024;
}
http {
 include mime.types;
 default_type application/octet-stream;
 sendfile on;
 keepalive_timeout 65;
 server {
  listen 80;
  server_name localhost;
  location / {
   root html;
   index index.html index.htm;
  }
  error_page 500 502 503 504 /50x.html;
  location = /50x.html {
   root html;
  }
 }
}
[root@AnSheng conf]# egrep -v "#|^$" nginx.conf.default nginx.conf

Four, add the following tags and content inside the server tag of the nginx configuration file

location /logs {
 alias /application/nginx-1.9.7/logs;
 #Nginx log directory
 autoindex on;
 #Enable directory browsing functionality
 autoindex_exact_size off;
 #Default is on, shows the exact size of the file, unit is bytes
 #Show the approximate size of the file, units are kB or MB or GB
 autoindex_localtime on;
 #Default is off, the displayed file time is GMT time.
 #After changing to on, the displayed file time is the server time of the file
 add_header Cache-Control no-store;
 #Do not save temporary files in the browser
}

Five, enable opening log files in the browser, if not enabled, clicking on the file will download instead of opening

[root@AnSheng conf]# vim mime.types
types {
 text/html html htm shtml;
 text/log log;
 text/css css;
 text/xml xml;
 .............

Six, check the syntax and then make the nginx configuration take effect, view in the browser

[root@AnSheng conf]# /application/nginx-1.9.7/sbin/nginx -t
nginx: the configuration file /application/nginx-1.9.7/conf/nginx.conf syntax is ok
nginx: configuration file /application/nginx-1.9.7/conf/nginx.conf test is successful
[root@AnSheng conf]# /application/nginx-1.9.7/sbin/nginx -s reload

Откройте браузер, введите домен или IP, добавьте logs в конце и нажмите на файл, чтобы открыть его. Если логи могут быть легко просмотрены другими, это не очень безопасно, поэтому мы должны добавить уровень аутентификации пользователей Nginx.

VII. Установите httpd-tools, используемые для генерации учетных данных

[root@AnSheng ~]# yum -y install httpd-tools

VIII. Создание учетной записи для аутентификации

[root@AnSheng ~]# htpasswd -c /application/nginx-1.9.7/conf/loguser loguser
Новый пароль:
Повторите новый пароль:
Добавление пароля для пользователя loguser
#Пароль нужно ввести дважды

IX. Редактировать файл конфигурации Nginx, добавить следующий контент в section logs

location /logs {
 ......
 alias PATH;
 autoindex on;
 autoindex_exact_size off;
 autoindex_localtime on;
 add_header Cache-Control no-store;
 auth_basic "Restricted";
 #Аутентификация Nginx
 auth_basic_user_file /application/nginx-1.9.7/conf/loguser;
 #Файл сохранения учетных данных для аутентификации
}

X. При следующем открытии будет предложено ввести имя пользователя и пароль, только после успешной авторизации можно будет просматривать.

XI. Обобщение

Вот все шаги для использования Nginx для просмотра логов браузера в реальном времени, надеюсь, это поможет вам в изучении или работе. Если у вас есть вопросы, вы можете оставить комментарии для обсуждения.

Вам может понравиться