Главная > Blog's evolution, General > Легендарное возвращение

Легендарное возвращение

В это уже никто не верил, но это произошло! Я снова осилил набросать пару строк! Собственно, что произошло?! Просто обновились тарифы на VPS(не бойтесь, ссылка нереферальная). Загвоздка заключалась в том, что существующий сервер нельзя перевести на новую линейку тарифов, только заказ нового VPS-сервера. Плюс ко всему отсутствие Gentoo в списке доступных ОС, но у меня имеется опыт работы с deb-подобными дитрибутивами, предпочтение отдал Debian`у.

     Сначала хотел бы поделиться впечатлениями по поводу использования gentoo на сервере. Да, очень удобно в плане управления и настройкой системы, но бОльшая сложность поддержки системы(не буду расписывать, верьте на слово, вы хлебнёте…) и гораздо больше времени на первоначальную установку, т.к. всё  это дело нужно скомпилить(может занять много времени, если у Вас слабое железо).  Но если вы не боитесь трудностей, то получите мощнейший инструмент во всем его величии(Portage и прочее) и вскоре сможете захватить весь мир!

     Что же, на борту имеем debian-7.0-x86_64-minimal и нет ничего проще, чем взять и перенести готовый сайт! Сначала прилижим систему, ведь мы ужасно ленивы и любим удобство, и комфорт. Приступим!

Обновимся:

apt-get update && apt-get upgrade

Для начала настроим ssh

# Правим файл /etc/ssh/sshd_config
# Сменим стандартный порт;
Port 9022
# Оставим только вторую версию протокола;
Protocol 2
# Запретим root`a;
# не забывая создать нового юзера
PermitRootLogin no

Вторым делом нам нужны автодополнения команд:

apt-get install bash-completion

И в файл /etc/bash.bashrc:

if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi

#вставить перед
export PATH

Немного подправим /etc/inputrc:

# alternate mappings for "page up" and "page down" to search the history
"\e[5~": history-search-backward
"\e[6~": history-search-forward

Конечно же после терминала gentoo, который из коробки божественно прекрасен, я попал на обсолютное безрыбье, которое нужно срочно украсить.

В файле /root/.bashrc, должны иметь как минимум:

# /root/.bashrc
[[ $- != *i* ]] && return
alias ls='ls --color=auto'
#PS1='[\u@\h \W]\$ '
#PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '
PS1='\[\033[01;31m\]\h\[\033[01;34m\] \W \$\[\033[00m\]'

и /home/user/.bashrc причешите где-нибудь так:

# ~/.bashrc
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac

# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options

HISTCONTROL=ignoreboth

# append to the history file, don't overwrite it
shopt -s histappend

# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000

# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize

# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar

# make less more friendly for non-text input files, see lesspipe(1)
#[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm*|rxvt*|Eterm|aterm|kterm|gnome*|interix)
PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:${PWD/$HOME/~}\007"'
;;
screen)
PROMPT_COMMAND='echo -ne "\033_${USER}@${HOSTNAME%%.*}:${PWD/$HOME/~}\033\"'
;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 > /dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi

if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac

# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'

#alias grep='grep --color=auto'
#alias fgrep='fgrep --color=auto'
#alias egrep='egrep --color=auto'
fi

# some more ls aliases
#alias ll='ls -l'
#alias la='ls -A'
#alias l='ls -CF'

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi

# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi

С терминалом разобрались, приступим к установке самого вебсервера. Я использую связку nginx+mysql+php-fpm и ssmtp для рассылки почты:

apt-get install nginx mysql-server php5-fpm php5-mysql openssl ssmtp

Первым делом сгенерируем ssl-сертификат для nginx:

mkdir /etc/nginx/ssl
cd /etc/nginx/ssl

#немного обезапасим наши сертификаты
chown www-data:www-data /etc/nginx/ssl
chmod 700 /etc/nginx/ssl

openssl req -new -x509 -days 9999 -nodes -out cert.pem -keyout cert.key
#ответьте на вопросы или нет

Приступим к настройке mysql:

mysql -u root -p
#вводим пароль

#создаем базу данных
CREATE DATABASE wordpress;

#создаем пользователя
CREATE USER username@localhost;

#даем права пользователю на управление БД
GRANT ALL PRIVILEGES ON wordpress.* TO username@localhost IDENTIFIED BY 'password';

#обновляем и выходим
FLUSH PRIVILEGES;
quit

В моем случае уже есть архив с настроенной wordpress, остается просто распаковать его. Для этих дел у меня есть маленький скрипт, можно глянуть тут.
На всякий случай покажу настройку wordpress c нуля.

#Скачиваем последнюю версию и распаковываем в /tmp
cd /tmp
wget http://wordpress.org/latest.tar.gz
tar xvf latest.tar.gz

Правим конфиги

cp wordpress/wp-config-sample.php wordpress/wp-config.php
vim wordpress/wp-config.php
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');

/** MySQL database username */
define('DB_USER', 'username');

/** MySQL database password */
define('DB_PASSWORD', 'password');

Перемещаем и выставляем хозяина

mkdir -p /var/www
cp -r wordpress/* /var/www
cd /var/www
chown -R www-data:www-data .
usermod -a -G www-data

Остается настроить nginx.
Подготавливаем виртуальный хост

cp /etc/nginx/sites-available/default /etc/nginx/sites-available/wordpress
vim /etc/nginx/sites-available/wordpress
server {
listen 80;

root /var/www;
index index.php index.html index.htm;

server_name example.com;

location / {
try_files $uri $uri/ /index.php?q=$uri&$args;
}

error_page 404 /404.html;

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/www;
}

# pass the PHP scripts to FastCGI server listening on a UNIX socket
location ~ \.php$ {
#fastcgi_pass 127.0.0.1:9000;
# With php5-fpm:
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
}

Разрешаем vhost:

ln -s /etc/nginx/sites-available/wordpress /etc/nginx/sites-enabled/wordpress
rm /etc/nginx/sites-enabled/default

Перезапустим Nginx и PHP:

service nginx restart
service php5-fpm restart

Совсем забыл сказать про ssmtp, если вы захотите использовать почту, а вы захотите, то нет смысла поднимать свой mail-сервер. Можно создать бесплатный ящик, скажем, на gmail.com и через него делать расстылку. Пример настройки для ящика user@gmail.com:

# правим файл /etc/ssmtp/ssmtp.conf
root=user@gmail.com
mailhub=smtp.gmail.com:587
hostname=smtp.gmail.com:587
UseSTARTTLS=YES
AuthUser=user@gmail.com
AuthPass=пароль от почты
FromLineOverride=YES

# в файл /etc/ssmtp/revaliases
root:user@gmail.com:smtp.gmail.com:587

Собственно всё, аналогично можно проделать и для mediawiki.

  1. Пока что нет комментариев.

What is 6 + 14 ?
Please leave these two fields as-is:
Чтобы продолжить вы должны решить простое уравнение (так мы узнаем, что вы человек) :-)