- Корректная настройка Nginx в Mac OS?
- Configuring Logging
- Setting Up the Error Log
- Setting Up the Access Log
- Enabling Conditional Logging
- Usecase: Sampling TLS Parameters
- Logging to Syslog
- Live Activity Monitoring
- Логи error_log и access_log в Nginx
- Лог ошибок error_log
- Лог доступа access_log
- Запись в syslog
- Включение режима debug
Корректная настройка Nginx в Mac OS?
Здравствуйте, помогите пожалуйста разобраться!
Пытаюсь настроить Nginx в Mac OS.
В /usr/local/etc/nginx/servers/ создаю файл mysite_nginx.conf . В /private/etc/host добавил 127.0.0.1 mysite . Запускаю Nginx, захожу по url mysite:8888, а статика не отображается.
Команда nginx -t :
P.S. До этого использовал Nginx лишь в Ubuntu 16.04, где кастомные настройки для своего проекта создавались в папке /etc/nginx/sites-available/mysite_nginx.conf .
- Вопрос задан более трёх лет назад
- 8421 просмотр
Nginx слушает 80 порт, но вы продожаете ходить в 8888, т.е. мимо nginx.
А вообще, nginx точно запустился, а то сообщения об ошибках вообще-то не совместимы с нормальной работой.
Алексей Тен, вы правы я обращаясь по порту 8888 в url я проходил мимо Nginx. Написал в url-ке mysite без порта и все открылось как надо. На счет ошибок не могу сам понять в чем проблема. Проверил файлы error.log и nginx.pid по указанным адресам и они существуют. Заходил в файл /usr/local/etc/nginx/nginx.conf и там были закоментированы следующие поля:
Я их разкомментировал, и перезагрузил nginx (Команда sudo nginx -s reload).
Запустил команду nginx -t но к сожалению выдает те же ошибки. Есть идеи как исправить ситуацию?
Тестировать тоже надо используя sudo
Алексей Тен, В чем существенная разница между sudo nginx -t и nginx -t ? Понятно sudo выполняет команду от имени администратора.
Без sudo не хватает прав на открытие файлов логов.
Источник
Configuring Logging
Capture detailed information about errors and request processing in log files, either locally or via syslog.
This article describes how to configure logging of errors and processed requests in NGINX Open Source and NGINX Plus.
Setting Up the Error Log
NGINX writes information about encountered issues of different severity levels to the error log. The error_log directive sets up logging to a particular file, stderr , or syslog and specifies the minimal severity level of messages to log. By default, the error log is located at logs/error.log (the absolute path depends on the operating system and installation), and messages from all severity levels above the one specified are logged.
The configuration below changes the minimal severity level of error messages to log from error to warn :
In this case, messages of warn , error crit , alert , and emerg levels are logged.
The default setting of the error log works globally. To override it, place the error_log directive in the main (top-level) configuration context. Settings in the main context are always inherited by other configuration levels ( http , server , location ). The error_log directive can be also specified at the http, stream, server and location levels and overrides the setting inherited from the higher levels. In case of an error, the message is written to only one error log, the one closest to the level where the error has occurred. However, if several error_log directives are specified on the same level, the message are written to all specified logs.
Note: The ability to specify multiple error_log directives on the same configuration level was added in NGINX Open Source version 1.5.2.
Setting Up the Access Log
NGINX writes information about client requests in the access log right after the request is processed. By default, the access log is located at logs/access.log, and the information is written to the log in the predefined combined format. To override the default setting, use the log_format directive to change the format of logged messages, as well as the access_log directive to specify the location of the log and its format. The log format is defined using variables.
The following examples define the log format that extends the predefined combined format with the value indicating the ratio of gzip compression of the response. The format is then applied to a virtual server that enables compression.
Another example of the log format enables tracking different time values between NGINX and an upstream server that may help to diagnose a problem if your website experience slowdowns. You can use the following variables to log the indicated time values:
- $upstream_connect_time – The time spent on establishing a connection with an upstream server
- $upstream_header_time – The time between establishing a connection and receiving the first byte of the response header from the upstream server
- $upstream_response_time – The time between establishing a connection and receiving the last byte of the response body from the upstream server
- $request_time – The total time spent processing a request
All time values are measured in seconds with millisecond resolution.
When reading the resulting time values, keep the following in mind:
- When a request is processed through several servers, the variable contains several values separated by commas
- When there is an internal redirect from one upstream group to another, the values are separated by semicolons
- When a request is unable to reach an upstream server or a full header cannot be received, the variable contains 0 (zero)
- In case of internal error while connecting to an upstream or when a reply is taken from the cache, the variable contains — (hyphen)
Logging can be optimized by enabling the buffer for log messages and the cache of descriptors of frequently used log files whose names contain variables. To enable buffering use the buffer parameter of the access_log directive to specify the size of the buffer. The buffered messages are then written to the log file when the next log message does not fit into the buffer as well as in some other cases.
To enable caching of log file descriptors, use the open_log_file_cache directive.
Similar to the error_log directive, the access_log directive defined on a particular configuration level overrides the settings from the previous levels. When processing of a request is completed, the message is written to the log that is configured on the current level, or inherited from the previous levels. If one level defines multiple access logs, the message is written to all of them.
Enabling Conditional Logging
Conditional logging allows excluding trivial or unimportant log entries from the access log. In NGINX, conditional logging is enabled by the if parameter to the access_log directive.
This example excludes requests with HTTP status codes 2xx (Success) and 3xx (Redirection):
Usecase: Sampling TLS Parameters
Many clients use TLS versions older than TLS 1.3. Though many ciphers are declared insecure, older implementations still use them; ECC certificates offer greater performance than RSA, but not all clients can accept ECC. Many TLS attacks rely on a “man in the middle” who intercepts the cipher negotiation handshake and forces the client and server to select a less secure cipher. Therefore, it’s important to configure NGINX Plus to not support weak or legacy ciphers, but doing so may exclude legacy clients.
You can evaluate the SSL data obtained from the client and determine what proportion of clients get excluded if support for older SSL protocols and ciphers is removed.
The following configuration example logs the SSL protocol, cipher, and User-Agent header of any connected TLS client, assuming that each client selects the most recent protocol and most secure ciphers it supports.
In this example, each client is identified by its unique combination of IP address and User-Agent.
Define the custom log format sslparams that includes the version of the SSL protocol ( $ssl_protocol ), ciphers used in the connection ( $ssl_cipher ), the client IP address ( $remote_addr ), and the value of standard User Agent HTTP request field ( $http_user_agent ):
Define a key-value storage that will keep the IP address of the client and its User Agent, for example, clients :
Create a variable, for example, $seen for each unique combination of $remote_addr and User-Agent header:
View the log file generated with this configuration:
Process the log file to determine the spread of data:
In this output, low‑volume, less secure ciphers are identified:
Then you can check the logs to determine which clients are using these ciphers and then make a decision about removing these ciphers from the NGINX Plus configuration.
For more information about sampling requests with NGINX conditional logging see the blog post.
Logging to Syslog
The syslog utility is a standard for computer message logging and allows collecting log messages from different devices on a single syslog server. In NGINX, logging to syslog is configured with the syslog: prefix in error_log and access_log directives.
Syslog messages can be sent to a server= which can be a domain name, an IP address, or a UNIX-domain socket path. A domain name or IP address can be specified with a port to override the default port, 514 . A UNIX-domain socket path can be specified after the unix: prefix:
In the example, NGINX error log messages are written to a UNIX domain socket at the debug logging level, and the access log is written to a syslog server with an IPv6 address and port 1234 .
The facility= parameter specifies the type of program that is logging the message. The default value is local7 . Other possible values are: auth , authpriv , daemon , cron , ftp , lpr , kern , mail , news , syslog , user , uucp , local0 . local7 .
The tag= parameter applies a custom tag to syslog messages ( nginx in our example).
The severity= parameter sets the severity level of syslog messages for access log. Possible values in order of increasing severity are: debug , info , notice , warn , error (default), crit , alert , and emerg . Messages are logged at the specified level and all more severe levels. In our example, the severity level error also enables crit , alert , and emerg levels to be logged.
Live Activity Monitoring
NGINX Plus provides a real-time live activity monitoring interface that shows key load and performance metrics of your HTTP and TCP upstream servers. See the Live Activity Monitoring article for more information.
To learn more about NGINX Plus, please visit the Products page.
Источник
Логи error_log и access_log в Nginx
Файлы логов — первое место, где нужно искать ошибки. Особенно если это касается веб-сервера. В Nginx всего два основных лога: error_log и access_log .
Лог ошибок error_log
Логирование ошибок Nginx происходит в определенный файл, stderr или syslog. Он собирает все ошибки, которые произошли во время работы веб-сервера. По умолчанию он включен глобально:
error_log logs/error.log error;
Записываются только ошибки в файл по указанному пути
Для сбора только определенных ошибок необходимо разместить директиву в секции http, server, stream или location . А так можно логировать только критические ошибки и сигналы тревоги:
error_log logs/error.log warn;
Записываются ошибки уровня warn, error crit, alert, emerg
Лог доступа access_log
Лог доступа Nginx по умолчанию размещен в директории logs/access.log . В него записываются данные о запросах пользователей, как только эти запросы обработаны. Для изменения директории расположения лога используется директива access_log :
access_log logs/access.log combined;
Используется комбинированный формат
В расширенном виде access_log можно настроить по своим требованиям:
Задается пользовательский формат с записью времени подключения, TTFB, TTLB, времени обработки запроса
Также можно исключить ненужную информацию из лога:
Исключает запросы к HTTP со статусом 2ХХ (успешно) и 3ХХ (редирект)
Запись в syslog
Стандартная для UNIX-систем утилита syslog может собирать логи и различные сообщения разных процессов на одном сервере:
Перенаправляет информацию в syslog
Директива server указывает адрес сервера (здесь IPv6) и порт. А facility — специфические параметры программы: auth, authpriv, daemon, cron, ftp, lpr, kern, mail, news, syslog,user, uucp, local0 … local7.
Включение режима debug
При необходимости можно включить Nginx debug-режим записи логов, который обеспечивает расширенную информацию и полезен при решении серьезных проблем:
error_log logs/error.log debug;
Можно включить только для нужной секции или отдельных клиентов соединений
Этот текст был написан несколько лет назад. С тех пор упомянутые здесь инструменты и софт могли получить обновления. Пожалуйста, проверяйте их актуальность.
Highload нужны авторы технических текстов. Вы наш человек, если разбираетесь в разработке, знаете языки программирования и умеете просто писать о сложном!
Откликнуться на вакансию можно здесь .
Как перезапустить nginx после обновления конфигурации
Как и зачем используется заголовок Cache-control
Уменьшение размера картинок при сохранении качества
301 redirect в Nginx’e
Что такое Etag и как его настроить в Nginx
Как исправить ошибку 405 Not Allowed в Nginx
Причины и методы исправления ошибки Gateway Timeout, Nginx
Как настроить Nginx на максимальную эффективность
Где находится nginx.conf и пример настроек
Как использовать try_files в настройках Nginx’a
Основы оптимизации работы Web сервера
Работа приложения с несколькими бэкендами при помощи Nginx
Архитектурные принципы высоконагруженных приложений
Как пофиксить ошибку «110: connection timed out» while reading response header from upstream
Как исправить ошибку Primary script unknown в Nginx
Использование Nginx, как кэширующего сервера
Причины возникновения ошибки Ошибка 502 bad gateway в Nginx и методы исправления
Как решить ошибку upstream sent too big header while reading response header from upstream в Nginx
Как улучшить время получения первого байта и отзывчивость веб-сервера
Ошибка HTTP 413 (Request Entity Too Large Error) означает, что клиент отправил слишком большой запрос на сервер.
Примеры применения Javascript в Nginx’e
Как включить и использовать сжатие gzip в Nginx
Примеры использования Lua в Nginx для решения стандартных задач
Источник