← All posts

Nginx and Apache2. Installation and Quick Configuration!

nginx\_apache

Why Do You Need Nginx?

It is a web server designed primarily for serving static content (to take the load off the backend) and for use as a frontend. Apache can then be used as the backend to generate dynamic content.

Nginx can also be used in FastCGI mode, in which case you won’t need Apache. However, PHP has a number of problems in this mode, so php-fpm comes to the rescue!

More details about PHP-FPM in my article: Nginx. Using PHP in FastCGI Mode with php-fpm

Today, however, we’ll talk about installing it together with Apache, rather than using FastCGI mode. What’s more, our setup calls for these web servers to reside on the same server, so we’ll assign port 80 to Nginx and port 88 to Apache! web\_diagram\_1

Installing Apache and Nginx

Install Apache:


cd /usr/ports/www/apache2
make config
make install clean

Install Nginx:


cd /usr/ports/www/nginx
make config
make install clean

Configuring Nginx

Let’s edit the file /usr/local/etc/nginx/nginx.conf


# пользователь и группа от которого запускается процесс
user  www www;

# 3 рабочих процесса
worker_processes  3;

# Лог для ошибок
error_log  logs/error.log;

events {

    # максимум рабочих соединений
    worker_connections  1024;

    # Метод обработки соединений
    # kqueue — эффективный метод, используемый во FreeBSD
    # Подробнее http://sysoev.ru/nginx/docs/events.html
    use kqueue;
}

http {

    # Подключаем таблицу mime
    include       mime.types;

    # mime-тип по умолчанию
    default_type  application/octet-stream;

    # Формат лог файла
    #log_format  main  '$remote_addr - $remote_user [$time_local] $request '
    #                  '"$status" $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    # Лог доступа всего веб-сервера
    #access_log  logs/access.log  main;

    # Директива задаёт таймаут при чтении заголовка запроса клиента
    client_header_timeout  3m;

    # Директива задаёт таймаут при чтении тела запроса клиента
    client_body_timeout    3m;

    # Директива задаёт таймаут при передаче ответа клиенту
    send_timeout           3m;

    # Директива задаёт таймаут, в течение которого keep-alive соединение с клиентом не будет закрыто со стороны сервера
    keepalive_timeout      2m;

    # Директива разрешает или запрещает использовать sendfile()
    sendfile        on;

    # Директива разрешает или запрещает использовать опции TCP_NOPUSH во FreeBSD
    # Подробнее http://sysoev.ru/nginx/docs/http/ngx_http_core_module.html#keepalive_timeout
    #tcp_nopush     on;

    # Директива задаёт размер буфера для чтения заголовка запроса клиента
    #client_header_buffer_size    1k;

    # Директива задаёт максимальное число и размер буферов для чтения большого заголовка запроса клиента
    #large_client_header_buffers  4 4k;

    # Модуль позволяет описывать группы серверов, которые могут использоваться
    # в директивах proxy_pass и fastcgi_pass.
    upstream backend {
        # Директива задаёт имя и параметры сервера. Обратите внимание, мы будем
        # использовать имя "backend" в директиве proxy_pass
        server 127.0.0.1:88;
    }

    server {

        # Слушать 80 порт
        listen       80;

        # Использовать следующие хосты
        server_name  pyha.ru www.pyha.ru;

        # Кодировка
        #charset koi8-r;

        # Лог доступа для конкретного виртуального хоста
        #access_log  logs/host.access.log  main;

        # Максимальный размер тела запроса клиента
        client_max_body_size 101M;

                # Разруливаем статику и динамку, смотрите описание ниже в этой статье!
                location ~* \.(jpg|jpeg|gif|png|ico|css|bmp|swf|js)$ {
                        root /home/pyha/pyha.ru;
                }

                location ~ /\.ht {
                        deny  all;
                }

                location / {
                        proxy_pass http://backend/;
                        proxy_set_header Host $host;
                        proxy_set_header X-Real-IP $remote_addr;
                        proxy_set_header X-Forwarded-For $remote_addr;

                        proxy_connect_timeout 120;
                        proxy_send_timeout    120;
                        proxy_read_timeout    180;
                }

        # Адрес страницы 404-ой ошибки, далее все ошибки по аналогии
        #error_page  404              /404.html;

        # Аналогично 404, только при этом назначается псевдоним 50x.html для всех
        # 50x-тых ошибок и далее перенаправляется все на "root"
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            # корневая директория
            root   /usr/local/www/nginx-dist;
        }
    }
}

After configuring it, you need to restart Nginx

/usr/local/etc/rc.d/nginx restart

Nginx: Serving Static Content

web\_diagram\_2 These rules let us route requests for static and dynamic content


# Следующие расширения файлов (jpg, jpeg, gif, png, ico, css, bmp, swf и js) отдаются напрямую, без участия Apache.
location ~* \.(jpg|jpeg|gif|png|ico|css|bmp|swf|js)$ {
    root /home/pyha/pyha.ru;
}

# htaccess и htpasswd не отдаем
location ~ /\.ht {
       deny  all;
}

# Все остальное разруливает бекенд (Apache)
location / {

        # Адрес бекенда. Параметры бекенда перечислили в директиве "upstream" (см. выше в статье)
        proxy_pass http://backend/;

        # Заголовок Host
        proxy_set_header Host $host;

        # Заголовок X-Real-IP
        proxy_set_header X-Real-IP $remote_addr;

        # Заголовок X-Forwarded-For
        proxy_set_header X-Forwarded-For $remote_addr;

        # Директива задаёт таймаут для соединения с проксированным сервером, сек
        proxy_connect_timeout 120;

        # Директива задаёт таймаут при передаче запроса проксированному серверу, сек
        proxy_send_timeout    120;

        # Директива задаёт таймаут при чтении ответа проксированного сервера, сек
        proxy_read_timeout    180;
}

Configuring Apache

Edit the file /usr/local/etc/apache2/httpd.conf


# Меняем порт с 80 на 88
Listen 88

Do the same in httpd-vhosts.conf for your hosts.

If you get the following error: > [warn] (2)No such file or directory: > Failed to enable the ‘httpready’ Accept Filter then you should load the module # kldload accf_http More details here http://www.mydigitallife.info/2006/04/23/freebsd-apache-http-accept-filter-error/

Installing and Configuring RPAF, or Give Us the Correct REMOTE_ADDR!

Since we’ve added an extra element to the chain in the form of a frontend server, REMOTE_ADDR now contains not the user’s IP, but the IP address of the frontend server (where Nginx resides). So RPAF comes to the rescue: it takes the contents of the X-Forwarded-For header sent by the frontend and uses them to populate REMOTE_ADDR on the backend.

This way, the REMOTE_ADDR header once again contains the user’s IP!

Install the RPAF module


cd /usr/ports/www/mod_rpaf2
make install clean

mod_rpaf2 is for apache2, while the first Apache needs mod_rpaf

Configure RPAF: edit httpd.conf and add the following to the end of the file:


# Включаем модуль
RPAFenable On
# Доводит до ума X-Host
RPAFsethostname On
# Адрес фронтенда (nginx)
RPAFproxy_ips 82.146.61.55 127.0.0.1
# Имя отправляемого заголовка
RPAFheader X-Forwarded-For

After configuring it, you need to restart Apache

apachectl restart

Well, that seems to be everything. Check out the additional reading below and ask questions in the comments!

Useful Nginx Resources

Useful links
Sample nginx configuration
Mailing list
Lexa Software: nginx mailing list archive
Configuring virtual servers
A great article from Habr: Tuning nginx
A useful article about load balancing, optimization, and caching in Nginx: Introduction to nginx, Part 2: Other Features

Comments are closed. Read the original discussion in Russian →