Игорь Олемской — практические заметки по системному администрированию Linux CentOS

Архив тега ‘nginx’

nginx server status (перепечатка)

Комментариев нет

The stub_status module provides the ability to get some stats from nginx...

active connections — number of all open connections including connections to backends

server accepts handled requests — nginx accepted connections, handled connections (no one was closed just it was accepted), and handles requests (requests per connection = handles requests / handled connections)

reading — nginx reads request header

writing — nginx reads request body, processes request, or writes response to a client

waiting — keep-alive connections, actually it is (active — reading + writing)

Original news source

watching nginx server status (перепечатка)

Комментариев нет

Once you have turned on nginx stub_status and enabled access from localhost:

  location /nginx_status {<br />    stub_status on;<br />    access_log off;<br />    allow 127.0.0.1;<br />    deny all;<br />  }

You can now watch the the status realtime with:

watch -n1 'curl localhost/nginx_status 2>/dev/null'

read more

Django HTTPS Redirects (перепечатка)

Комментариев нет

This works for both HTTP and HTTPS where any front end web server such as nginx which handles the actual request sets a header when request comes via HTTPS. In Apache configuration you then use mod_setenvif to set the HTTPS variable, which Django then picks up to use for redirection.

With front end nginx server which handles SSL, set header «X-Forwarded-Proto=https» via:

  proxy_set_header X-Forwarded-Proto https;

On Apache, add directive:

  SetEnvIf X-Forwarded-Proto https HTTPS=1

The HTTPS variable is picked up as being special by mod_wsgi and it will fix the wsgi.url_scheme in WSGI environment which Django then uses for redirection.

This way you don't need to customize Django stack.

read more

Кэширование в nginx (перепечатка)

Комментариев нет

Включение кэширования средствами nginx позволяет повысить скорость отдачи часто используемых страниц в очень много раз. Фишка в том, что сгенерированная апачем страница сохраняется в виде готового html-файла на диске и при поступлении запроса на такой же урл (совпадение по md5) файл-кэш быстро отдается клиенту. Кэширование в nginx доступно с версии 0.7.44. Благо в репозитории EPEL уже штатно присутствует 0.8.
К настройке кэширования нужно относиться очень внимательно, потому что на динамических сайтах весьма высока вероятность обрубания функциональности сайта: перестанут работать корзины на сайтах-магазинах, поломаются счетчики просмотров и тд.
Самая простая настройка выглядит так:
Сначала в http-секции прописываем где будет лежать кэш, его размер и время устаревания:

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=myzone:16m inactive=7d max_size=1024m;

Чистить кэш nginx будет сам. Кстати, в процессе отладки вы можете просто ходить в эту папку и смотреть что там закэшировалось.
Кэш можно включить либо для определенного location либо для всего виртуального хоста.

proxy_no_cache $cookie_logged; #условия, при которых ответ не будет сохраняться в кэш
proxy_cache_bypass $cookie_logged; #условия, при которых ответ не будет браться из кэша
proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
proxy_pass_header Set-Cookie;#разрешает передавать от проксируемого сервера клиенту запрещённые для передачи строки
proxy_ignore_headers "Expires" "Cache-Control"; #запрещает обработку некоторых строк заголовка из ответа проксированного сервера
proxy_cache_valid 200 301 302 304 1h; #время кэширования для разных ответов
proxy_cache myzone; #включает кэширование и задает зону

В процессе настройки посмотрите какие куки и в какой момент отправляет пользователю ваше приложение.
В интернете можно найти готовые конфиги nginx-а для кэширования под различные популярные CMS.
“Тупой” вариант кэширования с большим сроком устаревания кэша можно использовать в момент DDOS-а, тогда есть шанс, что сервер справится с наплывом запросов и сайт хоть и потеряет в функциональности, но останется доступен для поисковых систем и не уронит в след за собой остальные сайты на этом сервере.

Nginx location and rewrite configuration made easy (перепечатка)

Комментариев нет

The best way to think of things is that as a request comes in, Nginx will scan through the configuration to find a “location” line that matches the request. There are TWO modes that nginx uses to scan through the configuration file: literal string matching and regular expression checks. Nginx first scans through ALL literal string location entries in the order that they occur in the configuration file, and secondly scans through ALL the regular expression location entries in the order that they occur in the configuration file. So be aware – location ordering order DOES matter...

Original news source

clear out nginx cache (перепечатка)

Комментариев нет

If you are switching out static content that have gotten cached in nginx, the head of the cached files usually stores the file path that can be greped for and the file removed. One you hit the url again, it will recreate the new cached file at the same location.

find /var/cache/nginx -type f -exec grep -l /path/to/oldfile.css {} \;

read more

Nginx — Fast and Secure Web Server (перепечатка)

Комментариев нет

Nginx is a fast and efficient web server. It can be configured to serve out files or be a reverse proxy depending on your application. What makes this web server different from Apache, Lighttpd or thttpd is the overall efficiency of the daemon, the number of configuration options and how easy it is to setup...

Original news source

PHP-FPM and NGINX (перепечатка)

Комментариев нет

Since PHP 5.3.3, the PHP-FPM engine is bundled. The php-fpm package is available in remi repository and will be soon in rawhide.

This entry show how to use it with the nginx web server.

My goal is to install a working web server, for local and packaged (RPM) applications, I will use phpMyAdmin as an example.
1. Installation :
yum --enablerepo=remi install php-fpm nginx phpMyAdminThis command will also install the apache web server, listening on port 80. I will not use it, but I will configure nginx to listen on port 82.
2... Lire PHP-FPM and NGINX

Watching nginx upstreams with collectd (перепечатка)

Комментариев нет

Already happy with nginx in front of Apache for a number of sites, I decided it was time to start testing nginx/fastcgi on my personal server (the serial crash test dummy of my web operations). The only problem: I have yet to find a sensible method of grabbing useful runtime information from the PHP fastcgi process itself, and if you can’t sensibly watch it, you can’t sensibly deploy it.

Original news source

read more

6 ways to kill your server – learning how to scale the hard way (перепечатка)

Комментариев нет

Learning how to scale isn't easy without any prior experience. Nowadays you have plenty of websites like highscalability.com to get some inspiration, but unfortunately there is no solution that fits all websites and needs. You still have to think on your own and find a concept that works for your requirements. So did I.