Nginx+apache22+PHP 5.2+ffmpeg+flvtool2

Я подумал о создании социальной сети для своего родного города в которой можно смотреть ролики, создавать музыкальные альбомы, слушать музыку он-лайн и так далее. Для начала необходимо создать платформу для нее. С последующей установкой (в следующей статье будет рассмотрена его установка) socengine 3.20. Приступим к установке необходимого программного обеспечения для будущей работы socengine.

Содержание:

Подготовка

Обновляем исходные коды и порты встроенной утилитой csup, пользуясь статьей Локальное и удаленное обновление FreeBSD

Прежде чем ставить программы идем править make.conf для добавления необходимых флагов компиляции.

cat /etc/make.conf
NO_GAMES= true          # скажем нет играм на сервере
NO_INET6= true          # откажем сборке протокола IP6
 
WITHOUT_X11=yes         # без x11
NO_GUI=yes              #
NO_X11=yes              #
NO_X=yes                #
 
WITHOUT_CUPS=yes
 
# для MYSQL сервера
DEFAULT_MYSQL_VER=50
PORTSDIR?=      /usr/ports
.if ${.CURDIR} == ${PORTSDIR}/databases/mysql50-server
WITH_CHARSET=utf8
WITH_COLLATION=utf8_bin
#WITH_LINUXTHREADS=yes
BUILD_OPTIMIZED=yes
BUILD_STATIC=yes
.endif
 
# для MYSQL клиента
.if ${.CURDIR} == ${PORTSDIR}/databases/mysql50-client
WITH_CHARSET=utf8
WITH_COLLATION=utf8_bin
BUILD_OPTIMIZED=yes
.endif

Выберем кодировку для MYSQL UTF-8 тогда не будет проблем с кириллицей для любых установленных сайтов.

Установка Apache

cd /usr/ports/www/apache22 && make install clean

Опции сборки:

     THREADS=on "Enable threads support in APR"
     MYSQL=off "Enable MySQL support for apr-dbd"
     PGSQL=off "Enable PostgreSQL support for apr-dbd"
     SQLITE=off "Enable SQLite support for apr-dbd"
     IPV6=on "Enable IPv6 support"
     BDB=off "Enable BerkeleyDB dbm"
     AUTH_BASIC=on "Enable mod_auth_basic"
     AUTH_DIGEST=on "Enable mod_auth_digest"
     AUTHN_FILE=on "Enable mod_authn_file"
     AUTHN_DBD=off "Enable mod_authn_dbd"
     AUTHN_DBM=on "Enable mod_authn_dbm"
     AUTHN_ANON=on "Enable mod_authn_anon"
     AUTHN_DEFAULT=on "Enable mod_authn_default"
     AUTHN_ALIAS=on "Enable mod_authn_alias"
     AUTHZ_HOST=on "Enable mod_authz_host"
     AUTHZ_GROUPFILE=on "Enable mod_authz_groupfile"
     AUTHZ_USER=on "Enable mod_authz_user"
     AUTHZ_DBM=on "Enable mod_authz_dbm"
     AUTHZ_OWNER=on "Enable mod_authz_owner"
     AUTHZ_DEFAULT=on "Enable mod_authz_default"
     CACHE=on "Enable mod_cache"
     DISK_CACHE=on "Enable mod_disk_cache"
     FILE_CACHE=on "Enable mod_file_cache"
     MEM_CACHE=off "Enable mod_mem_cache"
     DAV=on "Enable mod_dav"
     DAV_FS=on "Enable mod_dav_fs"
     BUCKETEER=off "Enable mod_bucketeer"
     CASE_FILTER=off "Enable mod_case_filter"
     CASE_FILTER_IN=off "Enable mod_case_filter_in"
     EXT_FILTER=off "Enable mod_ext_filter"
     LOG_FORENSIC=off "Enable mod_log_forensic"
     OPTIONAL_HOOK_EXPORT=off "Enable mod_optional_hook_export"
     OPTIONAL_HOOK_IMPORT=off "Enable mod_optional_hook_import"
     OPTIONAL_FN_IMPORT=off "Enable mod_optional_fn_import"
     OPTIONAL_FN_EXPORT=off "Enable mod_optional_fn_export"
     LDAP=off "Enable mod_ldap"
     AUTHNZ_LDAP=off "Enable mod_authnz_ldap"
     ACTIONS=on "Enable mod_actions"
     ALIAS=on "Enable mod_alias"
     ASIS=on "Enable mod_asis"
     AUTOINDEX=on "Enable mod_autoindex"
     CERN_META=on "Enable mod_cern_meta"
     CGI=on "Enable mod_cgi"
     CHARSET_LITE=on "Enable mod_charset_lite"
     DBD=off "Enable mod_dbd"
     DEFLATE=on "Enable mod_deflate"
     DIR=on "Enable mod_dir"
     DUMPIO=on "Enable mod_dumpio"
     ENV=on "Enable mod_env"
     EXPIRES=on "Enable mod_expires"
     HEADERS=on "Enable mod_headers"
     IMAGEMAP=on "Enable mod_imagemap"
     INCLUDE=on "Enable mod_include"
     INFO=on "Enable mod_info"
     LOG_CONFIG=on "Enable mod_log_config"
     LOGIO=on "Enable mod_logio"
     MIME=on "Enable mod_mime"
     MIME_MAGIC=on "Enable mod_mime_magic"
     NEGOTIATION=on "Enable mod_negotiation"
     REWRITE=on "Enable mod_rewrite"
     SETENVIF=on "Enable mod_setenvif"
     SPELING=on "Enable mod_speling"
     STATUS=on "Enable mod_status"
     UNIQUE_ID=on "Enable mod_unique_id"
     USERDIR=on "Enable mod_userdir"
     USERTRACK=on "Enable mod_usertrack"
     VHOST_ALIAS=on "Enable mod_vhost_alias"
     FILTER=on "Enable mod_filter"
     VERSION=on "Enable mod_version"
     PROXY=on "Enable mod_proxy"
     PROXY_CONNECT=on "Enable mod_proxy_connect"
     PATCH_PROXY_CONNECT=on "Patch proxy_connect SSL support"
     PROXY_FTP=off "Enable mod_proxy_ftp"
     PROXY_HTTP=on "Enable mod_proxy_http"
     PROXY_AJP=off "Enable mod_proxy_ajp"
     PROXY_BALANCER=off "Enable mod_proxy_balancer"
     PROXY_SCGI=off "Enable mod_proxy_scgi"
     SSL=on "Enable mod_ssl"
     SUEXEC=on "Enable mod_suexec"
     SUEXEC_RSRCLIMIT=off "SuEXEC rlimits based on login class"
     REQTIMEOUT=on "Enable mod_reqtimeout"
     CGID=on "Enable mod_cgid"

Установка PHP

Сразу обращу внимание на то, что не стоит ставить версию php 5.3, так как при работе с socengine наблюдались глюки и я сам первый раз напоролся на эти грабли.

cd /usr/ports/lang/php52 && make install clean

Опции сборки:

     CLI=on "Build CLI version"
     CGI=on "Build CGI version"
     APACHE=on "Build Apache module"
     DEBUG=off "Enable debug"
     SUHOSIN=on "Enable Suhosin protection system (not for jails)"
     MULTIBYTE=off "Enable zend multibyte support"
     IPV6=on "Enable ipv6 support"
     MAILHEAD=off "Enable mail header patch"
     REDIRECT=off "Enable force-cgi-redirect support (CGI only)"
     DISCARD=off "Enable discard-path support (CGI only)"
     FASTCGI=on "Enable fastcgi support (CGI only)"
     FPM=off "Enable fastcgi process manager (CGI only)"
     PATHINFO=on "Enable path-info-check support (CGI only)"

Установка PHP-extensions

Установим необходимые модули php-extensions:

cd /usr/ports/lang/php52-extensions && make install clean

Опции сборки:

     BCMATH=off "bc style precision math functions"
     BZ2=on "bzip2 library support"
     CALENDAR=off "calendar conversion support"
     CTYPE=on "ctype functions"
     CURL=on "CURL support"
     DBA=on "dba support"
     DBASE=off "dBase library support"
     DOM=on "DOM support"
     EXIF=on "EXIF support"
     FILEINFO=on "fileinfo support"
     FILTER=on "input filter support"
     FRIBIDI=on "FriBidi support"
     FTP=on "FTP support"
     GD=on "GD library support"
     GETTEXT=on "gettext library support"
     GMP=off "GNU MP support"
     HASH=on "HASH Message Digest Framework"
     ICONV=on "iconv support"
     IMAP=on "IMAP support"
     INTERBASE=off "Interbase 6 database support (Firebird)"
     JSON=on "JavaScript Object Serialization support"
     LDAP=off "OpenLDAP support"
     MBSTRING=on "multibyte string support"
     MCRYPT=on "Encryption support"
     MHASH=on "Crypto-hashing support"
     MING=off "ming shockwave flash support"
     MSSQL=on "MS-SQL database support"
     MYSQL=on "MySQL database support"
     MYSQLI=off "MySQLi database support"
     NCURSES=off "ncurses support (CLI only)"
     ODBC=off "unixODBC support"
     OPENSSL=on "OpenSSL support"
     PCNTL=off "pcntl support (CLI only)"
     PCRE=on "Perl Compatible Regular Expression support"
     PDF=on "PDFlib support (implies GD)"
     PDO=on "PHP Data Objects Interface (PDO)"
     PDO_SQLITE=on "PDO sqlite driver"
     PDO_MYSQL=on "PDO mysql driver"
     PGSQL=off "PostgreSQL database support"
     POSIX=on "POSIX-like functions"
     PSPELL=off "pspell support"
     READLINE=off "readline support (CLI only)"
     RECODE=off "recode support"
     SESSION=on "session support"
     SHMOP=on "shmop support"
     SIMPLEXML=on "simplexml support"
     SNMP=off "SNMP support"
     SOAP=on "SOAP support"
     SOCKETS=on "sockets support"
     SPL=on "Standard PHP Library"
     SQLITE=on "sqlite support"
     SYBASE_CT=off "Sybase database support"
     SYSVMSG=off "System V message support"
     SYSVSEM=off "System V semaphore support"
     SYSVSHM=off "System V shared memory support"
     TIDY=off "TIDY support"
     TOKENIZER=on "tokenizer support"
     WDDX=off "WDDX support (implies XML)"
     XML=on "XML support"
     XMLREADER=on "XMLReader support"
     XMLRPC=on "XMLRPC-EPI support"
     XMLWRITER=on "XMLWriter support"
     XSL=off "XSL support (Implies DOM)"
     YAZ=on "YAZ support (ANSI/NISO Z39.50)"
     ZIP=on "ZIP support"
     ZLIB=on "ZLIB support"

Мод mod_rpaf2

Соберем данный модуль.

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

MySQL

Установим и настроим MYSQL:

/usr/ports/databases/mysql50-server && make install clean

Настроим MYSQL и изменим пароль суперпользователя.

/usr/local/bin/mysql_install_db
chown -R mysql /var/db/mysql/
cp /usr/local/share/mysql/my-large.cnf  /usr/local/etc/my.cnf
/usr/local/etc/rc.d/mysql-server onestart
/usr/local/bin/mysqladmin -u root password 'новый пароль'

Изменим конфигурационный файл MYSQL:

# The following options will be passed to all MySQL clients
[client]
#password       = your_password
port            = 3306
socket          = /tmp/mysql.sock
 
# The MySQL server
[mysqld]
port            = 3306
socket          = /tmp/mysql.sock
skip-locking
key_buffer = 256M
max_allowed_packet = 1M
table_cache = 256
sort_buffer_size = 1M
read_buffer_size = 1M
read_rnd_buffer_size = 4M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size= 16M
# Try number of CPU's*2 for thread_concurrency
thread_concurrency = 2
 
skip-federated
log-bin=mysql-bin
server-id       = 1
 
[mysqldump]
quick
max_allowed_packet = 16M
 
[mysql]
no-auto-rehash
# Remove the next comment character if you are not familiar with SQL
#safe-updates
 
[isamchk]
key_buffer = 128M
sort_buffer_size = 128M
read_buffer = 2M
write_buffer = 2M
 
[myisamchk]
key_buffer = 128M
sort_buffer_size = 128M
read_buffer = 2M
write_buffer = 2M
 
[mysqlhotcopy]
interactive-timeout

Утилита ffmpeg

Установим саму утилиту для обработки видео ffmpeg, но тут появились проблемы.

cd /usr/ports/multimedia/ffmpeg

Версия в портах:

Port:   ffmpeg-0.6_3,1
Path:   /usr/ports/multimedia/ffmpeg
Info:   Realtime audio/video encoder/converter and streaming server
Maint:  _mm@FreeBSD.org
B-deps: binutils-2.20.1_3 damageproto-1.2.0 dri2proto-2.2..
WWW:    _http://ffmpeg.mplayerhq.hu/

Эта версия у меня не все форматы кодировала, может быть из-за того что ключи при конвертировании поменялись, может надо было лезть в код и править что то, но я поступил иначе :) Откатываемся на стабильную и рабочую версию ffmpeg при помощи утилиты portdowngrade.

/usr/ports/ports-mgmt/portdowngrade
make DEFAULT_CVS_SERVER="anoncvs@anoncvs1.FreeBSD.org:/home/ncvs" install clean

После установки portdowngrade откатываем нам нужный порт на нужную версию

cd /usr/ports
portdowngrade multimedia/ffmpeg
 
portdowngrade 0.6 by Heiner Eichmann
Please note, that nothing is changed in the ports tree
unless it is explicitly permitted in step 6!
 
Seeking port multimedia/ffmpeg ...
 
Found several matches:
1: multimedia/ffmpeg
2: multimedia/ffmpeg-devel
3: multimedia/ffmpeg2theora
4: multimedia/ffmpegthumbnailer
 
Please choose one: 1
 
Downgrading port: multimedia/ffmpeg
 
Step 1: Checking out port from CVS repository
CVS root directory: anoncvs@anoncvs1.FreeBSD.org:/home/ncvs
 
Step 2: Reading the port history from the CVS repository
 
Step 3: Analyzing the port history from the CVS repository
Step 4: Load port version numbers and present results
Keys: <space> : next page                      d : details
            p : previous page
      <enter> : leave presentation and downdgrade if wanted
===============================
number         date         portversion  comment
    1  2010/08/01 20:41:25  0.6_3        - Fix architecture recognition [1]
    2  2010/07/27 18:53:42  0.6_2        Add VP8 codec support via libvpx and enable by default
    3  2010/07/25 16:18:15  0.6_1        Add missing files to PORTDOCS
    4  2010/07/24 16:38:14  0.6          - Update ffmpeg to 0.6
    5  2010/07/24 15:30:14  0.5.2_3      - Update x264 to 20100624 (build 98)
    6  2010/06/09 16:38:59  0.5.2_2      - Support SSSE3 by default
    7  2010/06/09 16:24:45  0.5.2_2      - Fix CFLAGS
    8  2010/06/06 20:43:54  0.5.2_1      Bump PORTREVISION for ports that depend on libogg, directly or indirectly
    9  2010/05/30 09:17:59  0.5.2        - Update to 0.5.2
   10  2010/04/21 12:56:46  0.5.1_3      - Update x264 to shared library version 85
   11  2010/04/18 20:41:52  0.5.1_2      - Add ssse3 support to OPTIONS
   12  2010/04/18 12:07:45  0.5.1_2      - Fix mmx/sse support in amd64 package [1]
   13  2010/03/27 00:13:31  0.5.1_1      Begin the process of deprecating sysutils/rc_subr by
   14  2010/03/24 18:44:18  0.5.1_1      - Update schroedinger to 1.0.9
   15  2010/03/10 14:03:01  0.5.1        - Fix configure option if building WITH_FAAC
   16  2010/03/10 11:00:00  0.5.1        - Update to 0.5.1
   17  2010/01/19 11:24:04  0.5_2        - Unbreak build if recent multimedia/v4l-compat is installed
   18  2009/12/31 11:15:30  0.5_2        - Move x11grab to OPTIONS as this requires x11, disable by default
   19  2009/10/16 11:24:04  0.5_1        - fix VUPEN/ADV-2009-2678
   20  2009/08/12 10:30:16  0.5          - Add ffmpeg-devel to CONFLICTS
   21  2009/08/12 08:43:17  0.5          - Update ffmpeg to 0.5
   22  2009/07/06 21:25:53  unknown      Bump PORTREVISION after libogg and libvorbisfile major version increment.
   23  2009/03/31 13:58:16  unknown      - Update x264 to 0.0.20081218
   24  2009/03/24 16:58:56  unknown      - Add MAKE_JOBS_SAFE to support SMP compilation
   25  2009/03/16 19:38:08  unknown      - Fix 4xm Processing Memory Corruption Vulnerability
   26  2009/02/21 15:51:14  unknown      - Chase audio/faad shlib bump
   27  2008/09/07 03:31:58  unknown      Force ffserver in to the background.
   28  2008/09/05 15:20:46  unknown      - Fix OPTIMIZED_CFLAGS option on gcc 4.2 (at least): explicitly disable
   29  2008/08/17 02:58:21  unknown      Fix build when ARH_NV or ARM_WB is defined
   30  2008/08/14 22:08:02  unknown      Enable the img_resample (old) code even if ffmpeg is built with libswscale
   31  2008/08/11 04:33:45  unknown      Append -I${includedir}/ffmpeg on to the Cflags in the pkg-config files.
   32  2008/08/11 02:41:45  unknown      Fix the plist after the recent commit.
   33  2008/08/10 19:46:42  unknown      Build libswscale by default once again.  I could not reproduce any problems
   34  2008/08/05 03:02:39  unknown      Fix compat headers installation, bump the PORTREVISION.
   35  2008/07/28 21:17:38  unknown      Install all the ffmpeg headers in a compat location to fix build of many ports
   36  2008/07/27 23:51:20  unknown      Update to 2008-07-27 snapshot
   37  2008/04/27 10:22:56  unknown      - move knobs into OPTIONS, make (almost) everything selectable
Total lines: 124. Command:
Enter version number to change port to (0: exit): 5
 
 
Step 5: Checking out choosen date of the port from the CVS repository
 
Step 6: Modifying the port
Port: multimedia/ffmpeg
at : 2010/07/24 15:30:14
Type 'yes' to bring the port to the state of the date above
or 'no' to exit without changing anything. Note, that this only changes
the port, not the installed software! yes or no:yes
 
The port has been set to the selected version. Install it if you wish.
If you have portupgrade installed, you should run
 
portsdb -Uu
 
now, to see the changes in the ports database. In any case
 
portupgrade -f ffmpeg
 
will install the changed port. Note: if you run cvsup, the port
is changed back to the choosen label!

Проверим что получилось:

PORTNAME=       ffmpeg
PORTVERSION=    0.5.2
PORTREVISION=   3

Установим нужный порт:

cd /usr/ports/multimedia/ffmpeg && make install clean

Опции сборки:

     AMR_NB=off "AMR Narrow Band encoder"
     AMR_WB=off "AMR Wide Band encoder"
     DIRAC=off "Dirac codec via libdirac"
     FAAC=on "FAAC mp4/aac audio encoder"
     FAAD=on "FAAD mp4/aac audio decoder"
     FFSERVER=on "Build and install ffserver"
     GSM=off "GSM audio codec"
     IPV6=on "IPV6 network support"
     LAME=on "LAME MP3 encoder"
     OPENJPEG=on "JPEG 2000 decoder"
     OPTIMIZED_CFLAGS=on "Additional optimizations"
     SCHROEDINGER=on "Dirac codec via libschroedinger"
     SDL=off "SDL support (build ffplay)"
     SPEEX=off "Speex audio decoder"
     SSSE3=on "Enable ssse3 support"
     THEORA=on "Theora encoder (implies OGG)"
     VHOOK=off "Video hook support"
     VORBIS=on "Vorbis encoder via libvorbis (implies OGG)"
     X11GRAB=off "enable X11 grabbing"
     X264=on "H.264 encoder"
     XVID=on "Xvid encoder via xvidcore"

Будьте особо внимательны при выборе опций, не стоит спешить, тогда все будет работать корректно.

Дополнительные модули

Установим модуль php-ffmpeg.

cd /usr/ports/graphics/php5-ffmpeg && make install clean

И утилиту flvtool2, которая будет заниматься созданием превью и записью метаданных видео.

cd /usr/ports/multimedia/ruby-flvtool2 && make install clean

Ставим memcached.

cd /usr/ports/databases/memcached && make install clean

Устанавливаем расширение pecl-memcache.

cd /usr/ports/databases/pecl-memcache && make install clean

Nginx и Apache

Установим Nginx:

cd /usr/ports/www/nginx-devel && make install clean

Опции сборки:

     DEBUG=off "Enable nginx debugging"
     DEBUGLOG=off "Enable debug log (--with-debug)"
     FILE_AIO=off "Enable file aio"
     IPV6=off "Enable IPv6"
     GOOGLE_PERFTOOLS=off "Enable google perftools module"
     HTTP_MODULE=on "Enable HTTP module"
     HTTP_ADDITION_MODULE=on "Enable http_addition module"
     HTTP_CACHE_MODULE=on "Enable http_cache module"
     HTTP_DAV_MODULE=off "Enable http_webdav module"
     HTTP_FLV_MODULE=on "Enable http_flv module"
     HTTP_GEOIP_MODULE=off "Enable http_geoip module"
     HTTP_GZIP_STATIC_MODULE=on "Enable http_gzip_static module"
     HTTP_IMAGE_FILTER_MODULE=on "Enable http_image_filter module"
     HTTP_PERL_MODULE=on "Enable http_perl module"
     HTTP_RANDOM_INDEX_MODULE=on "Enable http_random_index module"
     HTTP_REALIP_MODULE=on "Enable http_realip module"
     HTTP_REWRITE_MODULE=on "Enable http_rewrite module"
     HTTP_SECURE_LINK_MODULE=off "Enable http_secure_link module"
     HTTP_SSL_MODULE=on "Enable http_ssl module"
     HTTP_STATUS_MODULE=on "Enable http_stub_status module"
     HTTP_SUB_MODULE=on "Enable http_sub module"
     HTTP_XSLT_MODULE=off "Enable http_xslt module"
     MAIL_MODULE=on "Enable IMAP4/POP3/SMTP proxy module"
     MAIL_IMAP_MODULE=on "Enable IMAP4 proxy module"
     MAIL_POP3_MODULE=on "Enable POP3 proxy module"
     MAIL_SMTP_MODULE=on "Enable SMTP proxy module"
     MAIL_SSL_MODULE=on "Enable mail_ssl module"
     WWW=on "Enable html sample files"
     CACHE_PURGE_MODULE=on "3rd party cache_purge module"
     ECHO_MODULE=on "3rd party echo module"
     HEADERS_MORE_MODULE=off "3rd party headers_more module"
     HTTP_ACCEPT_LANGUAGE=on "3rd party accept_language module"
     HTTP_ACCESSKEY_MODULE=off "3rd party http_accesskey module"
     HTTP_AUTH_PAM_MODULE=off "3rd party http_auth_pam module"
     HTTP_AUTH_REQ_MODULE=on "3rd party http_auth_request module"
     HTTP_EVAL_MODULE=off "3rd party eval module"
     HTTP_FANCYINDEX_MODULE=on "3rd party http_fancyindex module"
     HTTP_GUNZIP_FILTER=on "3rd party http_gunzip_filter module"
     HTTP_MOGILEFS_MODULE=off "3rd party mogilefs module"
     HTTP_MP4_H264_MODULE=on "3rd party mp4/h264 module"
     HTTP_NOTICE_MODULE=on "3rd party notice module"
     HTTP_PUSH_MODULE=on "3rd party push module"
     HTTP_REDIS_MODULE=off "3rd party http_redis module"
     HTTP_RESPONSE_MODULE=on "3rd party http_response module"
     HTTP_UPLOAD_MODULE=on "3rd party upload module"
     HTTP_UPLOAD_PROGRESS=on "3rd party uploadprogress module"
     HTTP_UPSTREAM_FAIR=on "3rd party upstream fair module"
     HTTP_UPSTREAM_HASH=on "3rd party upstream hash module"
     HTTP_UPSTREAM_KEEPALIVE=on "3rd party upstream keepalive module"
     HTTP_ZIP_MODULE=on "3rd party http_zip module"
     MEMC_MODULE=on "3rd party memc (memcached) module"
     PASSENGER_MODULE=off "3rd party passenger module"
     SLOWFS_CACHE_MODULE=on "3rd party slowfs_cache module"
     SUPERVISORD_MODULE=off "3rd party supervisord module"
     UDPLOG_MODULE=off "3rd party udplog (syslog) module"

Итак , приступим к настройке связки nginx+apache. Принцип работы такой:

Настроим конфигурационный файл апача и приведем его к такому виду:

ee /usr/local/etc/apache22/httpd.conf
Listen 88 # меняем порт , который будет слушать апач
 
#<Directory />  # Эту секцию закомментируем
#    AllowOverride None
#    Order deny,allow
#    Deny from all
#</Directory>
 
<IfModule dir_module>
    DirectoryIndex index.html index.php # добавляем тип расширения
</IfModule>
LoadModule rpaf_module        libexec/apache22/mod_rpaf.so # После установки, строка закомментирована. 
Include etc/apache22/extra/httpd-vhosts.conf # расскоментируем для виртуальных хостов
RPAFenable On
RPAFsethostname On
RPAFproxy_ips 127.0.0.1 IP сервера
RPAFheader X-Forwarded-For
 
AddType application/x-httpd-php .php## включаем php
AddType application/x-httpd-php-source .phps

Идем настраивать виртульный хост

ee /usr/local/etc/apache22/extra/httpd-vhosts.conf

Меняем в конфигурационном файле

NameVirtualHost 127.0.0.1:88
<VirtualHost 127.0.0.1:88>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "/usr/local/www/domain"
    ServerName domain
    ServerAlias _www.domain
    ErrorLog "/var/log/domain-error_log"
    CustomLog "/var/log/domain-access_log" common
</VirtualHost>

На этом настройка закончена. Далее будем настраивать Nginx.
Внесем основные параметры, а виртуальные хосты вынесем в другую директорию, например vhosts.

mkdir /usr/local/etc/nginx/vhosts 
ee /usr/local/etc/nginx/nginx.conf

nginx.conf

# пользователь от кого запущен nginx
user  www www; 
# количество воркеров как и количество ядер
worker_processes 2;
worker_priority -5;
worker_rlimit_nofile 51200;
 
error_log  logs/error.log info;
 
#pid        logs/nginx.pid;
 
events {
# число одновременных коннектов
    worker_connections  2000;
}
 
http {
    include       mime.types;
    default_type  application/octet-stream;
 
    log_format  main  '$remote_addr - $remote_user [$time_local] $status '
                      '"$request" $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "http_x_forwarded_for"';
 
    access_log  logs/access.log  main;
 
sendfile on;
tcp_nopush on;
tcp_nodelay on;
send_lowat 12000;
 
client_header_timeout  3m;
client_body_timeout    3m;
send_timeout           3m;
keepalive_timeout  65;
client_header_buffer_size    1k;
large_client_header_buffers  4 4k;
 
output_buffers   4 32k;
 
#Compressing
gzip on;
proxy_send_timeout   90;
proxy_read_timeout   90;
proxy_buffer_size    8k;
proxy_buffers     16 64k;
proxy_buffering on;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 10m;
#proxy_connect_timeout 120s;
proxy_redirect     off;
 
 
include  vhosts/*.conf;

Идем в vhosts и создаем конфигурационный файл для виртуалхоста:

cd vhosts
vi domain.conf

Пример моей конфигурации:

server {
        listen       80;
        server_name  domain.org _www.domain.org;
 
        access_log  logs/domain.org.access.log  main;
        open_file_cache             max=100000 inactive=40s;
        open_file_cache_valid       60s;
        open_file_cache_min_uses    2;
        open_file_cache_errors      on;
 
        # Main location
        location / {
            proxy_pass         _http://127.0.0.1:88/;
            proxy_redirect     off;
 
            proxy_set_header   Host             $host;
            proxy_set_header   X-Real-IP        $remote_addr;
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
 
            client_max_body_size       1000m;
            client_body_buffer_size    128k;
 
            proxy_connect_timeout      90;
            proxy_send_timeout         90;
            proxy_read_timeout         90;
 
            proxy_buffer_size          4k;
            proxy_buffers              4 32k;
            proxy_busy_buffers_size    64k;
            proxy_temp_file_write_size 10m;
        }
## Эта директива отвечает за отдачу стриминга видео
        location ~ \.flv$ {
        flv;
        }
        # То что отдаем обрабатывать nginx, все что не попало , отдает апач
        location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|flv|rtf|js|swf|iso)$ {
            root   /usr/local/www/domain;
        }
 
    }

eAccelerator

Ставим ускоритель.

cd /usr/ports/www/eaccelerator && make install clean

Cоздаем директорию для кеша и назначаем права

root# mkdir /var/eaccelerator
root# chown www:www /var/eaccelerator
root# chmod 0700 /var/eaccelerator

Вносим изменения в php.ini

cd /usr/local/etc
cp php.ini-dist php.ini
vi php.ini 

И вносим параметры для включения модуля:

zend_extension="/usr/local/lib/php/20060613/eaccelerator.so"
eaccelerator.enable="1"
eaccelerator.shm_size="128"
eaccelerator.cache_dir="/var/eaccelerator"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max = "0"
eaccelerator.shm_ttl="3600"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

Дополнительная настройка системы

Приступаем к дополнительной настройки нашего сервера, идем править rc.conf для внесения нужных нам записей:

apache22_enable="YES"
accf_http_load="YES"
mysql_enable="YES"
memcached_enable="YES"
memcached_flags="-l 127.0.0.1"
nginx_enable="YES"

Настроим sysctl.conf

kern.sync_on_panic=1
kern.coredump=0
security.bsd.conservative_signals=1
security.bsd.unprivileged_proc_debug=0
security.bsd.unprivileged_read_msgbuf=0
security.bsd.unprivileged_get_quota=0
kern.ipc.shmmax=134217728
kern.ipc.shmall=32768
kern.ipc.semmap=256
kern.ipc.nmbclusters=262144
#########
kern.ipc.somaxconn=4096
 
# Shared memory // 7.2+ can use shared memory > 2Gb
kern.ipc.shmmax=2147483648
# Sockets
kern.ipc.maxsockets=204800
# Do not use lager sockbufs on 8.0
# ( _http://old.nabble.com/Significant-performance-regression-for-increased-maxsockbuf-on-8.0-RELEASE-tt26745981.html#a26745981 )
kern.ipc.maxsockbuf=262144
# Every socket is a file, so increase them
kern.maxfiles=204800
kern.maxfilesperproc=200000
kern.maxvnodes=200000
# Small send space is useful for http servers that serve small files
# Autotuned since 7.x
#net.inet.tcp.sendspace=16384
 
# Increase portrange
# For outgoing connections only. Good for seed-boxes and ftp servers.
net.inet.ip.portrange.first=1024
net.inet.ip.portrange.last=65535
# Security
net.inet.ip.redirect=0
net.inet.ip.sourceroute=0
net.inet.ip.accept_sourceroute=0
net.inet.icmp.maskrepl=0
net.inet.icmp.log_redirect=0
net.inet.icmp.drop_redirect=1
net.inet.tcp.drop_synfin=1
# Security
net.inet.udp.blackhole=1
net.inet.tcp.blackhole=2
# Increases default TTL, sometimes useful
# Default is 64
net.inet.ip.ttl=128
# Lessen max segment life to conserve resources
# ACK waiting time in miliseconds (default: 30000 from RFC)
net.inet.tcp.msl=5000
# Max bumber of timewait sockets
net.inet.tcp.maxtcptw=200000
# Should be increased when you have A LOT of files on server
# (Increase until vfs.ufs.dirhash_mem becomes lower)
vfs.ufs.dirhash_maxmem=67108864
 
# Note from commit _http://svn.freebsd.org/base/head@211031 :
# For systems with RAID volumes and/or virtualization envirnments, where
# read performance is very important, increasing this sysctl tunable to 32
# or even more will demonstratively yield additional performance benefits.
vfs.read_max=32

Запуск

Запускаем сервисы

/usr/local/etc/rc.d/apache22 start
/usr/local/etc/rc.d/nginx start
/usr/local/etc/rc.d/memcached start

Проверяем запустились ли корректно сервисы:
httpd:

ps ax | grep httpd
45476  ??  Ss     0:01.72 /usr/local/sbin/httpd -DNOHTTPACCEPT
45477  ??  I      0:00.00 /usr/local/sbin/httpd -DNOHTTPACCEPT
45478  ??  I      1:57.17 /usr/local/sbin/httpd -DNOHTTPACCEPT
45479  ??  S      0:58.02 /usr/local/sbin/httpd -DNOHTTPACCEPT
45480  ??  I      1:20.96 /usr/local/sbin/httpd -DNOHTTPACCEPT
45481  ??  I      0:41.50 /usr/local/sbin/httpd -DNOHTTPACCEPT
45482  ??  I      0:52.08 /usr/local/sbin/httpd -DNOHTTPACCEPT
45483  ??  S      1:06.11 /usr/local/sbin/httpd -DNOHTTPACCEPT
45496  ??  I      0:28.35 /usr/local/sbin/httpd -DNOHTTPACCEPT
51859  ??  I      0:24.14 /usr/local/sbin/httpd -DNOHTTPACCEPT
55619   0  R+     0:00.00 grep httpd

nginx:

ps ax | grep nginx
51854  ??  Is     0:00.00 nginx: master process /usr/local/sbin/nginx
51855  ??  S<     0:05.98 nginx: worker process (nginx)
51856  ??  S<     0:03.93 nginx: worker process (nginx)
55628   0  R+     0:00.00 grep nginx

ps ax | grep memcached
 1121  ??  Is     0:02.31 /usr/local/bin/memcached -l 127.0.0.1 -d -u nobody
55630   0  RL+    0:00.00 grep memcached

В директории сайта создаем файл phpinfo.php и проверяем, работает ли php и загрузились ли все необходимые модули.

<?php
phpinfo();
?>

Если что то не так или не запустилось то, смотрим логи.

Установку ФТП сервера описывать не буду, у каждого свой вкус.
Вот вариант настройки Pure-FTPd+MySQL+Web

Дополнительные материалы
Ваша оценка: Нет Средняя: 5 (17 голосов)

Спасибо!

Спасибо за статью, хоть кто-то толково написал, все работает, лишь осталось указать кодировку виртуалхосту.

Блин, как похудеть?

Кучу перепробовала ни одна не работает
Народ посоветуйте хорошую диету так чтоб особо не напрягаться но и чтоб интересно было?

Ответить на комментарий | igNix.ru

That is very fascinating, You are an overly professional blogger.
I have joined your rss feed and look ahead to looking for extra of
your excellent post. Also, I've shared your web site in my social networks

Ответить на комментарий | igNix.ru

Mobile units and became entertainment for the iPad end users,
Stardom: The A-listing game.

Во забубенил

Спасибо тебе огромное статья класная :)

accf_http_load="YES"

accf_http_load="YES"
надо указывать не в rc.conf а в loader.conf

Ответить на комментарий | igNix.ru

When some one searches for his required thing, thus he/she desires to be available
that in detail, thus that thing is maintained over here.

А на какой версий freebsd вы все это установили?

А на какой версий freebsd вы все это установили?

я в принципе делаю тоже самое для установки ffmpeg на freebsd 7.1 и этот компилируется с ошибками...

wow wolike server

server sphere of warcraft, outwit recreation of the year, and all years old.
welcome to mistress of ceremonies on my position

где слить socengine

Ну настроил ты вебсервер, а где слить socengine?

Последние статьи

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer