Устанавливаем и настраиваем Nginx
sudo apt-get install nginx
sudo vim /etc/nginx/sites-available/default
Файл default
server {
listen 80;
server_name localhost;
#access_log /var/log/nginx/localhost.access.log;
charset utf-8;
rewrite ^/sitemap\.xml$ /sitemap last;
rewrite ^/robots\.txt$ /robots.php last;
## Default location
location / {
root /var/www;
index index.php;
if (!-f $request_filename) {
rewrite ^(.*)$ /index.php?q=$1 last;
break;
}
# if ($slow) {
# limit_rate 10k;
# }
if (!-d $request_filename) {
#rewrite ^(.*)$ /includes/load.php?q=$1 last;
#break;
}
# Задаем максимальное количество одновременных соединений для одной сессии. По сути, это число задает максимальное количество соединений с одного IP
limit_conn addr 5;
}
location /nginx_status {
root /var/cache/munin/www;
stub_status on;
access_log off;
}
## Images and static content is treated different
location ~* ^.+\.(jpg|jpeg|gif|css|png|js|ico|xml)$ {
access_log off;
expires 30d;
root /var/www;
}
## Parse all .php file in the /var/www directory
location ~ \.php$ {
root /var/www;
fastcgi_split_path_info ^(.+\.php)(.*)$;
fastcgi_pass backend;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name;
include fastcgi_params;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_intercept_errors on;
fastcgi_ignore_client_abort off;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
}
## Disable viewing .htaccess & .htpassword
location ~ /\.ht {
deny all;
}
}
upstream backend {
server 127.0.0.1:9000;
}
server {
server_name ~(?=www\.);
if ( $host ~* "www.(.*)"){
set $unwww $1;
}
rewrite ^ $scheme://$unwww$request_uri permanent;
}
Файл /etc/nginx/nginx.conf
user www-data;
worker_processes 2;
worker_rlimit_nofile 51200;
worker_priority -5;
pid /var/run/nginx.pid;
events {
worker_connections 16384;
use epoll;
# multi_accept on;
}
http {
client_max_body_size 100m;
##
# Basic Settings
##
ignore_invalid_headers on;
reset_timedout_connection on;
client_header_timeout 15;
client_body_timeout 15;
send_timeout 5;
server_tokens off;
output_buffers 16 32k;
postpone_output 1460;
connection_pool_size 4096;
large_client_header_buffers 512 8k;
client_header_buffer_size 1k;
client_body_buffer_size 32k;
# client_max_body_size 5;
request_pool_size 64k;
# limit connections per IP
#limit_req_zone $binary_remote_addr zone=qulag:16m rate=2r/s;
#limit_req_zone $binary_remote_addr zone=qulag1:16m rate=1r/s;
#limit_zone gulag $binary_remote_addr 64m;
# Описываем зону (slimits), в которой будут храниться состояния сессий. Зона размером 1 Мб может хранить около 32000 состояний, мы устанавливаем ее размер равным 5 Мб
limit_conn_zone $binary_remote_addr zone=addr:10m;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 30 15;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log off;
#access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
##
# nginx-naxsi config
##
# Uncomment it if you installed nginx-naxsi
##
#include /etc/nginx/naxsi_core.rules;
##
# nginx-passenger config
##
# Uncomment it if you installed nginx-passenger
##
#passenger_root /usr;
#passenger_ruby /usr/bin/ruby;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Устанавливаем и настраиваем php-fpm
sudo apt-get install php5-fpm php5-dev php5-mysql php5-curl php5-gd php5-mcrypt php5-sqlite php5-xmlrpc php5-xsl php5-common
Установка APC
sudo apt-get install php-apc
sudo /etc/init.d/php5-fpm restart
Установка eAccelerator + настройка под php-fpm
1. Скачиваем, распаковываем и устанавливаем eAccelerator 0.9.6.1
cd /tmp
wget http://bart.eaccelerator.net/source/0.9.6.1/eaccelerator-0.9.6.1.tar.bz2
tar xvfj eaccelerator-0.9.6.1.tar.bz2
cd eaccelerator-0.9.6.1
sudo phpize
./configure --enable-eaccelerator=shared
sudo make
sudo make install
Помните у вас должен быть установлен php-dev
2. Настраиваем php.ini. Для этого в папке конфигурации php создаем файл eaccelerator.ini
sudo nano /etc/php5/fpm/conf.d/eaccelerator.ini
И прописываем настройки eAccelerator'а
extension="eaccelerator.so"
; Максимальный размер кеша в мегабайтах
eaccelerator.shm_size="512"
; Корневой каталог для хранения кеша
eaccelerator.cache_dir="/var/cache/eaccelerator"
eaccelerator.enable="1"
; Подключить или отключить встроенный оптимайзер
; которые увеличивает скорость выполнения кода
eaccelerator.optimizer="1"
; Включаем проверку модификации PHP файлов. Поставьте
; "1" если требуется, чтобы проверялись все модифицированные
; файлы и перекомпиливались заново.
eaccelerator.check_mtime="1"
; Режим отладки. Если поставить 1 или вообще
; забыть упомянуть этот параметр, при большой
; посещаемости загадит логи Apache за считанные часы.
eaccelerator.debug="0"
; Здесь можно определить можно определить, какие
; файлы должны быть кешированы. По-умолчанию если
; здесь ничего не указано, то кешируются все файлы.
; Для расширенного использования прочитайте документацию.
eaccelerator.filter=""
; Максимально допустимое значение которое может быть
; отправлено в разделяемую память. По-умолчанию,
; "ноль" - без ограничений. Размер указывается в байтах,
; но можно указать приставки, например: 10240, 10K, 1M.
eaccelerator.shm_max="0"
; Когда акселлератору потребуется отправить в разделяемую
; память какой-то объект и при этом в памяти для этого
; не окажется места, он попытается удалить файлы, которые
; не были запрошены в течении последних "shm_ttl" секунд.
; По-умолчанию, это значение равно "0" - не удалять ничего.
eaccelerator.shm_ttl="0"
; Когда акселлератору потребуется отправить в разделяемую
; память какой-то объект и при этом в памяти для этого
; не окажется места, он попытается удалить старые скрипты,
; если предыдущие такие попытки были не больше, чем
; "shm_prune_period" секунд назад.По-умолчанию, это значение
; равно "0" - не удалять ничего.
eaccelerator.shm_prune_period="0"
; Включить или отключить кеширование скомпиленных скриптов
; _только_ на диск. Этот параметр не влияет на данные сессий
; и кеширование контента. По-умолчанию, значение 0, что означает
; что данные будут кешироваться и в памяти и на диске.
eaccelerator.shm_only="0"
; Включить или отключить сжатие закешированного контента.
; По-умолчанию, "1" - сжимать.
eaccelerator.compress="0"
; Уровень сжатия. По-умолчанию, "9" - максимум.
eaccelerator.compress_level="3"
3. Создаем папку для кэша
sudo mkdir -p /var/cache/eaccelerator
sudo chmod 0777 /var/cache/eaccelerator
Вот и все eAccelerator установлен и настроен остается только перезагрузить php-fpm.
Настройка APC
(Нет смысла ставить вместе с eAccelerator)
Конфиг: /etc/php5/fpm/conf.d/apc.ini
extension="eaccelerator.so"
extension=apc.so
apc.enabled=1
;apc.stat = 0
apc.max_file_size=100M
apc.shm_size=256
apc.include_once_override=0
apc.num_files_hint=7000
apc.user_entries_hint=4096
;Allow 2 seconds after a file is created before it is cached to prevent users from seeing half-written/weird pages
apc.file_update_protection=2
apc.cache_by_default=1
apc.use_request_time=1
apc.slam_defense=0
;apc.mmap_file_mask=/tmp/apc/apc.XXXXXX
apc.stat_ctime=0
apc.canonicalize=1
apc.write_lock=1
apc.report_autofilter=0
apc.rfc1867=1
apc.rfc1867_prefix =upload_
apc.rfc1867_name=APC_UPLOAD_PROGRESS
apc.rfc1867_freq=10k
apc.rfc1867_ttl=3600
apc.lazy_classes=0
apc.lazy_functions=0
Установка MySQL
sudo apt-get install mysql-server
Устанавливаем модуль mysql для php5
sudo apt-get install php5-mysql
Для установки кодировки UTF-8 по умолчанию дописываем в /etc/mysql/my.conf
[client]
default-character-set=utf8
character-set-server = utf8
collation-server = utf8_general_ci
character-set-client = utf8
character-set-results = utf8
character-set-connection = utf8
[mysqld]
character_set_server=utf8
[server]
skip-character-set-client-handshake
Конфиг полностью:
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
#
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
default-character-set=utf8
#character-set-server = utf8
#collation-server = utf8_general_ci
#character-set-client = utf8
#character-set-results = utf8
#character-set-connection = utf8
# Here is entries for some specific programs
# The following values assume you have at least 32M ram
# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
large-pages
#
# * Basic Settings
#
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
wait_timeout=60
connect_timeout=10
interactive_timeout=120
join_buffer_size=1M
query_cache_size=128M
query_cache_limit=2M
max_allowed_packet=16M
table_cache=1024
sort_buffer_size=8M
read_buffer_size=8M
read_rnd_buffer_size=4M
key_buffer = 256M
key_buffer_size=2000M
myisam_sort_buffer_size = 2M
max_connections = 10000
open_files_limit = 100000
thread_cache_size = 50
bulk_insert_buffer_size = 512M
myisam_recover = 1
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address = 127.0.0.1
#
# * Fine Tuning
#
key_buffer = 1048M
thread_stack = 192K
thread_cache = 16
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover = BACKUP
max_user_connections = 4999
max_heap_table_size = 128M
tmp_table_size = 128M
net_buffer_length = 16K
#thread_concurrency = 10
#
# * Query Cache Configuration
#
query_cache_limit = 1M
query_cache_size = 32M
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file = /var/log/mysql/mysql.log
#general_log = 1
#
# Error logging goes to syslog due to /etc/mysql/conf.d/mysqld_safe_syslog.cnf.
#
# Here you can see queries with especially long duration
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
# other settings you may need to change.
#server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
expire_logs_days = 10
max_binlog_size = 1000M
#binlog_do_db = include_database_name
#binlog_ignore_db = include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem
#init_connect='SET NAMES utf8'
character_set_server=utf8
[mysqldump]
quick
quote-names
max_allowed_packet = 16M
[mysql]
#no-auto-rehash # faster start of mysql but no tab completition
[server]
skip-character-set-client-handshake
#init-connect='set NAMES utf8'
[isamchk]
key_buffer = 16M
#
# * IMPORTANT: Additional settings that can override those from this file!
# The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/
Создаем новую базу данных
mysqladmin create
Если вы хотите сменить root пароль для mysql:
sudo dpkg-reconfigure mysql-server-5.1
Установка memcached
Нам нужно всего лишь выполнить одну команду:
apt-get install memcached php5-memcache
Установка и настройка SSH
apt-get install ssh
В настройки /etc/ssh/sshd_config прописываем
# Change to no to disable tunnelled clear text passwords
PasswordAuthentication yes
/etc/sysctl.conf
# Set the number of pages to be used.
# Each page is normally 2MB, so a value of 40 = 80MB.
# Set it 512 or higher if you have lots of memory
vm.nr_hugepages=40
# Set the group number (mysql group number is 27) that is allowed to access this memory. The mysql user must be a member of this group.
vm.hugetlb_shm_group=113
# Increase the amount of shmem allowed per segment
# This depends upon your memory, remember your
kernel.shmmax = 68719476736
# Increase total amount of shared memory.
kernel.shmall = 4294967296
# decrease swap
vm.swappiness = 10.
vm.vfs_cache_pressure = 1000
Запускаем и тестируем
sudo /etc/init.d/memcached restart
sudo /etc/init.d/nginx restart
sudo /etc/init.d/php5-fpm restart
sudo /etc/init.d/mysql restart
#или service mysql restart
Настройки BIOS
Автоматически загружаться после восстановления напряжения в электросети
Заходим в Power Menagment -> AC Back Function -> Power ON