Обзор Типичных Конфигураций Для Nginx
17 Apr2006

В одном из предыдущих постов я рассказывал об очень мощном инструменте для Unix-администраторов – web/reverse proxy-сервере Nginx. Как я говорил, одна из главных проблем этого сервера – это недостаточная документированность для англоязычных пользователей. Имнно поэтому я решил написать эту статью, в которой перечислены типичные конфигурации для nginx и приведены примеры конфигурационных файлов для этих ситуаций.

Все приведенные конфигурационные файлы были протестированы на последней версии nginx, которая была собрана и проинсталлирована следующим набором команд:

1
2
3
 # ./configure --prefix=/usr/local/nginx --with-http_ssl_module
 # make
 # make install

Поэтому вы можете просто скачать пример, переименовать его в nginx.conf, поправить необходимые параметры, положить файл в /usr/local/nginx/conf/ и запустить Ваш сервер.

Использование nginx как простого web-сервера для статических файлов

Nginx может быть без особых усилий настроен на работу в качестве эффективного web-сервера для раздачи статических файлов. Я использую его в такой конфигурации в моих проектах на отдельных доменах типа images.someproject.com с которых раздаются картинки и другая статика.

Пример конфигурационного файла может быть скачан отсюда.

Использование nginx как web-сервера с поддержкой PHP

Если Вам необходима поддержка PHP в nginx, Вы можете настроить PHP на режим работы как FastCGI-сервер и направить при помощи nginx все запросы к PHP-скриптам на определенный FastCGI-порт (tcp/socket). Для реализации описанной схемы Вам необходимо запустить PHP как FastCGI-сервер при помощи какого-либо стороннего ПО. Например – spawn-fcgi из поставки lighttpd. (Примечание: Эта процедура будет детально описана в одном из моих следуюзих постов.)

Для включения поддержки вам нужно создать отдельную секцию location в конфигурационном файле:

1
2
3
4
5
6
7
8
9
10
11
12
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
  fastcgi_pass   127.0.0.1:12345;
  fastcgi_index  index.php;

  fastcgi_param  SCRIPT_FILENAME  /usr/local/nginx/html$fastcgi_script_name;
  fastcgi_param  QUERY_STRING     $query_string;
  fastcgi_param  REQUEST_METHOD   $request_method;
  fastcgi_param  CONTENT_TYPE     $content_type;
  fastcgi_param  CONTENT_LENGTH   $content_length;
}

Пример конфигурационного файла можно скасать здесь.

Using nginx as web server with SSI support

Server-Side Includes (aka SSI) is another interesting feature of nginx. As for now, following ssi instructions are supported: config, echo, if, include, set.

SSI support can be anabled by single line configuration command in your config file:

1
2
3
4
    location / {
        ssi  on;
        ...
    }

Sample configuration file can be downloaded here.

Using nginx as https-enabled web server

You need https-access to your Nginx-powered site? No problems! Nginx supports https and can be used to implement secured web-server with SSLv2, SSLv3 or TLSv1.

To enable https-support you should have certificate and key files. How to obtain them, you can read in SSL FAQ. When you will obtain them, you can enable ssl-module:

1
2
3
4
5
6
7
8
    server {
        listen               443;
        ssl                  on;
        ssl_certificate      /usr/local/nginx/conf/cert.pem;
        ssl_certificate_key  /usr/local/nginx/conf/cert.key;
        keepalive_timeout    70;
        ...
    }

Sample configuration file can be downloaded here.

Using nginx as reverse-proxy server before some another web-server

If you have some large web-site and you have noticed, that your Apache can not handle more load, you can put nginx before your primary web-server to use it as light reverse-proxy and as web-server to handle requests to static files.

Thanks to nginx flexibility, you can pass any types of requests to backend server by using location sections (all files, only dynamic content requests or some specific locations in your web-server tree):

1
2
3
4
location / {
    proxy_pass        http://localhost:8000/;
    proxy_set_header  X-Real-IP  $remote_addr;
}

Sample configuration file can be downloaded here.

Using nginx for virtual hosting platforms

One of the interesting use cases for Nginx is virtual hosting platform because it meets all requirements for good hosting server: it is efficient, it supports all popular virtual hosting methods and it has very good internal structure, so it can be easily extended in for any specific areas.

As for now, it is being used by many hosting companies as reverse proxy and I am using it on my free hosting service with millions unique visitors per day.

If you vant to try virtual hosting feature, you can create additional server sections in your config file (first section will be default):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
http {
    server {
        listen  192.168.10.1;
        listen  192.168.10.1:8000;

        server_name   one.example.com  www.one.example.com;
        ...
    }

    server {
        listen  192.168.10.1;
        listen  192.168.10.2:8000;
        listen  9000;

        server_name   two.example.com  www.two.example.com
                      three.example.com  www.three.example.com;
        ...
    }

    server {
        listen  9000;

        server_name   four.example.com  www.four.example.com;
        ...
    }
}

Sample configuration file for small virtual hosting can be downloaded here.

As you can see from my small overview, nginx is very flexible software and you can do many interesting things with it. If you have any comments, questions or suggestions, feel free to drop them here in comments for this article and I will try to answer for all of them.