вторник, 24 августа 2021 г.

oracle

 ---

# tasks file for cfg_oracle


- name: check os support

  fail: msg="UNSUPPORTED OS"

  when: not

        (( ansible_distribution             == "OracleLinux" or

        ansible_distribution                == "RedHat" or 

        ansible_distribution                == "CentOS" ) and 

        (ansible_distribution_major_version  == "7" or

        ansible_distribution_major_version  == "6")  and

        ansible_userspace_bits              == "64")


#- name: Debug exit check point

#  fail:


- name: Disabling firewalld

  service: name=firewalld state=stopped enabled=no


- name: Disabling selinux

  selinux: state=disabled


- name: Installing chrony

  yum: name=chrony state=present


- name: Stopping chrony

  service: name=chronyd state=stopped enabled=yes


- name: Creating minimal /etc/chrony.conf

  copy:

    src: chrony.conf

    dest: /etc

  when: ansible_distribution == "RedHat" or ansible_distribution == "CentOS"


- name: Starting chrony

  service: name=chronyd state=started enabled=yes


- name: Getting memory size

  shell: free -b | sed -n '2p' | cut -d ' ' -f 5

  register: mem


- name: Calculating KERNEL_SHMALL KERNEL_SHMMAX

  set_fact:

      KERNEL_SHMMAX: "{{ (mem.stdout|int / 2) |int }}"

      KERNEL_SHMALL: "{{ (mem.stdout|int / 2 / 4096) |int }}"


- name: Setting kernel values KERNEL_SHMALL, KERNEL_SHMMAX in /etc/sysctl.d/90-oracle.conf

  template:

    src=../templates/90-oracle.sysctl.conf.j2

    dest=/etc/sysctl.d/90-oracle.conf


- name: Applying kernel settings

  shell: sysctl -p -q



- name: Calculating SHMFS_SIZE

  set_fact:

    SHMFS_SIZE: "{{ (mem.stdout|int *9/10/1024/1024/1024) |int }}"


- name: Mounting shmfs

  mount:

    path: /dev/shm

    src: none

    fstype: tmpfs

    opts: size={{SHMFS_SIZE}}g

    state: mounted



- name: Creating group dba

  group: name=dba state=present gid=103


- name: Creating group oinstall

  group: name=oinstall state=present gid=104


- name: Creating group oper

  group: name=oper state=present gid=105


- name: Adding user oracle

  user: name=oracle groups=dba,oinstall,oper uid=103



- name: Getting root VG name

  shell: df /|tail -1|awk -F [/-] '{print $4}'

  register: root_vg


#- debug: msg={{root_vg}}


- name: Creating /db (30gb)

  lvol:

    vg: "{{root_vg.stdout}}"

    lv: db

    size: 30g

  when: root_vg.stdout != ""


- name: Creating directory /db

  file: path=/db state=directory


- name: Mounting /dev/{{root_vg.stdout}}/db to /db (checking that /dev/{{root_vg.stdout}}/db formated and valid and doesn't need to be formated)

  mount:

    path: /db

    src: /dev/{{root_vg.stdout}}/db

    fstype: ext4

    state: mounted

  ignore_errors: true


- name: Checking if /db is mounted

  shell: mount|grep /db

  register: is_db_mounted

  ignore_errors: true

  

#- debug: msg={{is_db_mounted}}

#- fail:


- name: Formating /dev/{{root_vg.stdout}}/db with mkfs.ext4

  shell: mkfs.ext4 /dev/{{root_vg.stdout}}/db

  when: is_db_mounted.rc != 0


- name: Mounting /dev/{{root_vg.stdout}}/db to /db

  mount:

    path: /db

    src: /dev/{{root_vg.stdout}}/db

    fstype: ext4

    state: mounted


- name: Setting permissions to oracle:dba on /db

  file: path=/db owner=oracle group=dba


- name: Creating /etc/oratab with owner oracle:dba

  file: path={{item}} owner=oracle group=dba state=touch

  with_items:

  - /etc/oratab

  - /etc/oraInst.loc


- name: Calculating memlock limit

  set_fact:

      memlock: "{{ (mem.stdout|int * 9 / 10240) |int }}"


- name: Generating /etc/security/limits.d/90-oracle.conf

  template:

    src=../templates/90-oracle-limits.conf.j2

    dest=/etc/security/limits.d/90-oracle.conf



- name: Copying default /usr/share/doc/device-mapper-multipath-0.4.9/multipath.conf to /etc

  shell: cp /usr/share/doc/device-mapper-multipath-0.4.9/multipath.conf /etc


- name: Enabling mpathconf

  shell: mpathconf --enable


- name: Enabling multipathd

  service: name=multipathd state=started enabled=yes


- name: Copying /etc/rc.d/rc.local

  copy: src=rc.local dest=/etc/rc.d mode=0755


- name: Setting relayhost in /etc/postfix/main.cf

  lineinfile:

    path: /etc/postfix/main.cf

    line: 'relayhost = [mxsmtp.homecredit.ru]'


- name: Enabling postfix

  service: name=postfix state=started enabled=yes


- name: Installing Oracle dependencies

  yum: name={{ item }} state=present

  with_items: "{{ DEP_PKG }}"


- name: Copying /etc/fonts/local.conf

  copy: src=local.conf dest=/etc/fonts/local.conf mode=0644


вторник, 31 марта 2020 г.

npm nodejs8

#!/usr/bin/env bash

{ # this ensures the entire script is downloaded #

nvm_has() {
  type "$1" > /dev/null 2>&1
}

nvm_install_dir() {
  command printf %s "${NVM_DIR:-"$HOME/.nvm"}"
}

nvm_latest_version() {
  echo "v0.33.11"
}

nvm_profile_is_bash_or_zsh() {
  local TEST_PROFILE
  TEST_PROFILE="${1-}"
  case "${TEST_PROFILE-}" in
    *"/.bashrc" | *"/.bash_profile" | *"/.zshrc")
      return
    ;;
    *)
      return 1
    ;;
  esac
}

#
# Outputs the location to NVM depending on:
# * The availability of $NVM_SOURCE
# * The method used ("script" or "git" in the script, defaults to "git")
# NVM_SOURCE always takes precedence unless the method is "script-nvm-exec"
#
nvm_source() {
  local NVM_METHOD
  NVM_METHOD="$1"
  local NVM_SOURCE_URL
  NVM_SOURCE_URL="$NVM_SOURCE"
  if [ "_$NVM_METHOD" = "_script-nvm-exec" ]; then
    NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm-exec"
  elif [ "_$NVM_METHOD" = "_script-nvm-bash-completion" ]; then
    NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/bash_completion"
  elif [ -z "$NVM_SOURCE_URL" ]; then
    if [ "_$NVM_METHOD" = "_script" ]; then
      NVM_SOURCE_URL="https://raw.githubusercontent.com/creationix/nvm/$(nvm_latest_version)/nvm.sh"
    elif [ "_$NVM_METHOD" = "_git" ] || [ -z "$NVM_METHOD" ]; then
      NVM_SOURCE_URL="https://github.com/creationix/nvm.git"
    else
      echo >&2 "Unexpected value \"$NVM_METHOD\" for \$NVM_METHOD"
      return 1
    fi
  fi
  echo "$NVM_SOURCE_URL"
}

#
# Node.js version to install
#
nvm_node_version() {
  echo "$NODE_VERSION"
}

nvm_download() {
  if nvm_has "curl"; then
    curl --compressed -q "$@"
  elif nvm_has "wget"; then
    # Emulate curl with wget
    ARGS=$(echo "$*" | command sed -e 's/--progress-bar /--progress=bar /' \
                            -e 's/-L //' \
                            -e 's/--compressed //' \
                            -e 's/-I /--server-response /' \
                            -e 's/-s /-q /' \
                            -e 's/-o /-O /' \
                            -e 's/-C - /-c /')
    # shellcheck disable=SC2086
    eval wget $ARGS
  fi
}

install_nvm_from_git() {
  local INSTALL_DIR
  INSTALL_DIR="$(nvm_install_dir)"

  if [ -d "$INSTALL_DIR/.git" ]; then
    echo "=> nvm is already installed in $INSTALL_DIR, trying to update using git"
    command printf '\r=> '
    command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" fetch origin tag "$(nvm_latest_version)" --depth=1 2> /dev/null || {
      echo >&2 "Failed to update nvm, run 'git fetch' in $INSTALL_DIR yourself."
      exit 1
    }
  else
    # Cloning to $INSTALL_DIR
    echo "=> Downloading nvm from git to '$INSTALL_DIR'"
    command printf '\r=> '
    mkdir -p "${INSTALL_DIR}"
    if [ "$(ls -A "${INSTALL_DIR}")" ]; then
      command git init "${INSTALL_DIR}" || {
        echo >&2 'Failed to initialize nvm repo. Please report this!'
        exit 2
      }
      command git --git-dir="${INSTALL_DIR}/.git" remote add origin "$(nvm_source)" 2> /dev/null \
        || command git --git-dir="${INSTALL_DIR}/.git" remote set-url origin "$(nvm_source)" || {
        echo >&2 'Failed to add remote "origin" (or set the URL). Please report this!'
        exit 2
      }
      command git --git-dir="${INSTALL_DIR}/.git" fetch origin tag "$(nvm_latest_version)" --depth=1 || {
        echo >&2 'Failed to fetch origin with tags. Please report this!'
        exit 2
      }
    else
      command git -c advice.detachedHead=false clone "$(nvm_source)" -b "$(nvm_latest_version)" --depth=1 "${INSTALL_DIR}" || {
        echo >&2 'Failed to clone nvm repo. Please report this!'
        exit 2
      }
    fi
  fi
  command git -c advice.detachedHead=false --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" checkout -f --quiet "$(nvm_latest_version)"
  if [ ! -z "$(command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" show-ref refs/heads/master)" ]; then
    if command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch --quiet 2>/dev/null; then
      command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch --quiet -D master >/dev/null 2>&1
    else
      echo >&2 "Your version of git is out of date. Please update it!"
      command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" branch -D master >/dev/null 2>&1
    fi
  fi

  echo "=> Compressing and cleaning up git repository"
  if ! command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" reflog expire --expire=now --all; then
    echo >&2 "Your version of git is out of date. Please update it!"
  fi
  if ! command git --git-dir="$INSTALL_DIR"/.git --work-tree="$INSTALL_DIR" gc --auto --aggressive --prune=now ; then
    echo >&2 "Your version of git is out of date. Please update it!"
  fi
  return
}

#
# Automatically install Node.js
#
nvm_install_node() {
  local NODE_VERSION_LOCAL
  NODE_VERSION_LOCAL="$(nvm_node_version)"

  if [ -z "$NODE_VERSION_LOCAL" ]; then
    return 0
  fi

  echo "=> Installing Node.js version $NODE_VERSION_LOCAL"
  nvm install "$NODE_VERSION_LOCAL"
  local CURRENT_NVM_NODE

  CURRENT_NVM_NODE="$(nvm_version current)"
  if [ "$(nvm_version "$NODE_VERSION_LOCAL")" == "$CURRENT_NVM_NODE" ]; then
    echo "=> Node.js version $NODE_VERSION_LOCAL has been successfully installed"
  else
    echo >&2 "Failed to install Node.js $NODE_VERSION_LOCAL"
  fi
}

install_nvm_as_script() {
  local INSTALL_DIR
  INSTALL_DIR="$(nvm_install_dir)"
  local NVM_SOURCE_LOCAL
  NVM_SOURCE_LOCAL="$(nvm_source script)"
  local NVM_EXEC_SOURCE
  NVM_EXEC_SOURCE="$(nvm_source script-nvm-exec)"
  local NVM_BASH_COMPLETION_SOURCE
  NVM_BASH_COMPLETION_SOURCE="$(nvm_source script-nvm-bash-completion)"

  # Downloading to $INSTALL_DIR
  mkdir -p "$INSTALL_DIR"
  if [ -f "$INSTALL_DIR/nvm.sh" ]; then
    echo "=> nvm is already installed in $INSTALL_DIR, trying to update the script"
  else
    echo "=> Downloading nvm as script to '$INSTALL_DIR'"
  fi
  nvm_download -s "$NVM_SOURCE_LOCAL" -o "$INSTALL_DIR/nvm.sh" || {
    echo >&2 "Failed to download '$NVM_SOURCE_LOCAL'"
    return 1
  } &
  nvm_download -s "$NVM_EXEC_SOURCE" -o "$INSTALL_DIR/nvm-exec" || {
    echo >&2 "Failed to download '$NVM_EXEC_SOURCE'"
    return 2
  } &
  nvm_download -s "$NVM_BASH_COMPLETION_SOURCE" -o "$INSTALL_DIR/bash_completion" || {
    echo >&2 "Failed to download '$NVM_BASH_COMPLETION_SOURCE'"
    return 2
  } &
  for job in $(jobs -p | command sort)
  do
    wait "$job" || return $?
  done
  chmod a+x "$INSTALL_DIR/nvm-exec" || {
    echo >&2 "Failed to mark '$INSTALL_DIR/nvm-exec' as executable"
    return 3
  }
}

nvm_try_profile() {
  if [ -z "${1-}" ] || [ ! -f "${1}" ]; then
    return 1
  fi
  echo "${1}"
}

#
# Detect profile file if not specified as environment variable
# (eg: PROFILE=~/.myprofile)
# The echo'ed path is guaranteed to be an existing file
# Otherwise, an empty string is returned
#
nvm_detect_profile() {
  if [ -n "${PROFILE}" ] && [ -f "${PROFILE}" ]; then
    echo "${PROFILE}"
    return
  fi

  local DETECTED_PROFILE
  DETECTED_PROFILE=''

  if [ -n "${BASH_VERSION-}" ]; then
    if [ -f "$HOME/.bashrc" ]; then
      DETECTED_PROFILE="$HOME/.bashrc"
    elif [ -f "$HOME/.bash_profile" ]; then
      DETECTED_PROFILE="$HOME/.bash_profile"
    fi
  elif [ -n "${ZSH_VERSION-}" ]; then
    DETECTED_PROFILE="$HOME/.zshrc"
  fi

  if [ -z "$DETECTED_PROFILE" ]; then
    for EACH_PROFILE in ".profile" ".bashrc" ".bash_profile" ".zshrc"
    do
      if DETECTED_PROFILE="$(nvm_try_profile "${HOME}/${EACH_PROFILE}")"; then
        break
      fi
    done
  fi

  if [ ! -z "$DETECTED_PROFILE" ]; then
    echo "$DETECTED_PROFILE"
  fi
}

#
# Check whether the user has any globally-installed npm modules in their system
# Node, and warn them if so.
#
nvm_check_global_modules() {
  command -v npm >/dev/null 2>&1 || return 0

  local NPM_VERSION
  NPM_VERSION="$(npm --version)"
  NPM_VERSION="${NPM_VERSION:--1}"
  [ "${NPM_VERSION%%[!-0-9]*}" -gt 0 ] || return 0

  local NPM_GLOBAL_MODULES
  NPM_GLOBAL_MODULES="$(
    npm list -g --depth=0 |
    command sed -e '/ npm@/d' -e '/ (empty)$/d'
  )"

  local MODULE_COUNT
  MODULE_COUNT="$(
    command printf %s\\n "$NPM_GLOBAL_MODULES" |
    command sed -ne '1!p' |                     # Remove the first line
    wc -l | command tr -d ' '                   # Count entries
  )"

  if [ "${MODULE_COUNT}" != '0' ]; then
    # shellcheck disable=SC2016
    echo '=> You currently have modules installed globally with `npm`. These will no'
    # shellcheck disable=SC2016
    echo '=> longer be linked to the active version of Node when you install a new node'
    # shellcheck disable=SC2016
    echo '=> with `nvm`; and they may (depending on how you construct your `$PATH`)'
    # shellcheck disable=SC2016
    echo '=> override the binaries of modules installed with `nvm`:'
    echo

    command printf %s\\n "$NPM_GLOBAL_MODULES"
    echo '=> If you wish to uninstall them at a later point (or re-install them under your'
    # shellcheck disable=SC2016
    echo '=> `nvm` Nodes), you can remove them from the system Node as follows:'
    echo
    echo '     $ nvm use system'
    echo '     $ npm uninstall -g a_module'
    echo
  fi
}

nvm_do_install() {
  if [ -n "${NVM_DIR-}" ] && ! [ -d "${NVM_DIR}" ]; then
    echo >&2 "You have \$NVM_DIR set to \"${NVM_DIR}\", but that directory does not exist. Check your profile files and environment."
    exit 1
  fi
  if [ -z "${METHOD}" ]; then
    # Autodetect install method
    if nvm_has git; then
      install_nvm_from_git
    elif nvm_has nvm_download; then
      install_nvm_as_script
    else
      echo >&2 'You need git, curl, or wget to install nvm'
      exit 1
    fi
  elif [ "${METHOD}" = 'git' ]; then
    if ! nvm_has git; then
      echo >&2 "You need git to install nvm"
      exit 1
    fi
    install_nvm_from_git
  elif [ "${METHOD}" = 'script' ]; then
    if ! nvm_has nvm_download; then
      echo >&2 "You need curl or wget to install nvm"
      exit 1
    fi
    install_nvm_as_script
  fi

  echo

  local NVM_PROFILE
  NVM_PROFILE="$(nvm_detect_profile)"
  local PROFILE_INSTALL_DIR
  PROFILE_INSTALL_DIR="$(nvm_install_dir | command sed "s:^$HOME:\$HOME:")"

  SOURCE_STR="\\nexport NVM_DIR=\"${PROFILE_INSTALL_DIR}\"\\n[ -s \"\$NVM_DIR/nvm.sh\" ] && \\. \"\$NVM_DIR/nvm.sh\"  # This loads nvm\\n"

  # shellcheck disable=SC2016
  COMPLETION_STR='[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion\n'
  BASH_OR_ZSH=false

  if [ -z "${NVM_PROFILE-}" ] ; then
    local TRIED_PROFILE
    if [ -n "${PROFILE}" ]; then
      TRIED_PROFILE="${NVM_PROFILE} (as defined in \$PROFILE), "
    fi
    echo "=> Profile not found. Tried ${TRIED_PROFILE-}~/.bashrc, ~/.bash_profile, ~/.zshrc, and ~/.profile."
    echo "=> Create one of them and run this script again"
    echo "   OR"
    echo "=> Append the following lines to the correct file yourself:"
    command printf "${SOURCE_STR}"
    echo
  else
    if nvm_profile_is_bash_or_zsh "${NVM_PROFILE-}"; then
      BASH_OR_ZSH=true
    fi
    if ! command grep -qc '/nvm.sh' "$NVM_PROFILE"; then
      echo "=> Appending nvm source string to $NVM_PROFILE"
      command printf "${SOURCE_STR}" >> "$NVM_PROFILE"
    else
      echo "=> nvm source string already in ${NVM_PROFILE}"
    fi
    # shellcheck disable=SC2016
    if ${BASH_OR_ZSH} && ! command grep -qc '$NVM_DIR/bash_completion' "$NVM_PROFILE"; then
      echo "=> Appending bash_completion source string to $NVM_PROFILE"
      command printf "$COMPLETION_STR" >> "$NVM_PROFILE"
    else
      echo "=> bash_completion source string already in ${NVM_PROFILE}"
    fi
  fi
  if ${BASH_OR_ZSH} && [ -z "${NVM_PROFILE-}" ] ; then
    echo "=> Please also append the following lines to the if you are using bash/zsh shell:"
    command printf "${COMPLETION_STR}"
  fi

  # Source nvm
  # shellcheck source=/dev/null
  \. "$(nvm_install_dir)/nvm.sh"

  nvm_check_global_modules

  nvm_install_node

  nvm_reset

  echo "=> Close and reopen your terminal to start using nvm or run the following to use it now:"
  command printf "${SOURCE_STR}"
  if ${BASH_OR_ZSH} ; then
    command printf "${COMPLETION_STR}"
  fi
}

#
# Unsets the various functions defined
# during the execution of the install script
#
nvm_reset() {
  unset -f nvm_has nvm_install_dir nvm_latest_version nvm_profile_is_bash_or_zsh \
    nvm_source nvm_node_version nvm_download install_nvm_from_git nvm_install_node \
    install_nvm_as_script nvm_try_profile nvm_detect_profile nvm_check_global_modules \
    nvm_do_install nvm_reset
}

[ "_$NVM_ENV" = "_testing" ] || nvm_do_install

} # this ensures the entire script is downloaded #

пятница, 14 апреля 2017 г.

ssmtp отправка почты с нескольких сайтов на одном хостинге

В примере используется почта для домена от Яндекса.
Для каждого пользователя (сайта) user1.tld и user2.tld настроена своя почта для домена.

Конфигураци SSMTP

Нужно создать несколько конфигов ssmtp для каждого VirtualHost

Конфигурация 1
nano /etc/ssmtp/ssmtp-user1.conf
root=mail@user1.tld
mailhub=smtp.yandex.ru:465
RewriteDomain=user1.tld
Hostname=mail@user1.tld
# Set this to never rewrite the "From:" line (unless not given) and to
# use that address in the "from line" of the envelope.
FromLineOverride=YES
AuthUser=mail@user1.tld
AuthPass=passwd
AuthMethod=LOGIN
UseTLS=YES
TLS_CA_File=/etc/pki/tls/certs/ca-bundle.crt
Debug=NO
Конфигурация 2
nano /etc/ssmtp/ssmtp-user2.conf
root=mail@user2.tld
mailhub=smtp.yandex.ru:465
RewriteDomain=user2.tld
Hostname=mail@user2.tld
# Set this to never rewrite the "From:" line (unless not given) and to
# use that address in the "from line" of the envelope.
FromLineOverride=YES
AuthUser=mail@user2.tld
AuthPass=passwd
AuthMethod=LOGIN
UseTLS=YES
TLS_CA_File=/etc/pki/tls/certs/ca-bundle.crt
Debug=NO

Вторая конфигурация SSMTP (Revaliases)
nano /etc/ssmtp/revaliases

root:mail@user1.tld:smtp.yandex.ru:465
root:mail@user2.tld:smtp.yandex.ru:465

Что бы письма были отправлены не от пользователя apache (www-data) изменим комментарий пользователю. 
Этот комментарий будет виден в имени отправителя.

chfn -f "Web Email" apache

Конфигурация APACHE 

Для каждой конфигурации сайта (VirtualHost) нужно указать конфигурацию ssmtp.

nano /etc/httpd/conf.d/user1.tld.conf

<VirtualHost *:8080>
ServerName user1.tld#****
</VirtualHost>
<Directory "/home/user1.tld/html">
php_admin_value sendmail_path "/usr/sbin/ssmtp -t -C/etc/ssmtp/ssmtp-user1.conf"
php_admin_value sendmail_from "mail@user1.tld"
#****
</Directory>

nano /etc/httpd/conf.d/user2.tld.conf

<VirtualHost *:8080>
ServerName user2.tld#****
</VirtualHost>
<Directory "/home/user2.tld/html">
php_admin_value sendmail_path "/usr/sbin/ssmtp -t -C/etc/ssmtp/ssmtp-user2.conf"
php_admin_value sendmail_from "mail@user2.tld"
#****
</Directory>

Перезапустить apache и проверить отправку писем
<?
mail('your@email.com', 'Test From Your-Site', 'Test Message from Sendmail by PHP');
?>

Настройка nginx+apache и нескольких VirtualHost


Конфигурация nginx


user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    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  /var/log/nginx/access.log  main;
    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;
    gzip  on;
    include /etc/nginx/conf.d/*.conf;
}

Конфиг httpd

***
Include conf.d/*.conf
User apache
Group apache
***

Пользователи

Имя пользователя = имя домена

adduser user.tldmkdir /home/user.tld/html
mkdir /home/user.tld/log
chown user.tld /home/user.tld/ -R
chgrp apache /home/user.tld/ -R
chmod 755 /home/user.tld/ -R
sudo usermod -a -G apache user.tldpasswd user.tld
Аналогично создаем пользователя для поддомена, в данном случае sub.user.tld.

этот шаг можно пропустить, если поддомены будут у одного пользователя и создаваться динамически

VirtualHost в httpd


Домен
nano /etc/httpd/conf.d/user.tld
<VirtualHost *:8080>
ServerName user.tld
ServerAlias www.user.tld
ServerAdmin webmaster@user.tld
ErrorLog /home/user.tld/log/error.log
CustomLog /home/user.tld/log/access.log combined
DocumentRoot /home/user.tld/html/
</VirtualHost>
<Directory "/home/user.tld/html">
Order deny,allow
Allow from all
</Directory>
Поддомен (этот шаг тоже пропускаем, если нужны динамические поддомены
в папке основного пользователя)
nano /etc/httpd/conf.d/sub.user.tld
<VirtualHost *:8080>
ServerName sub.user.tld
ServerAlias www.sub.user.tld
ServerAdmin webmaster@user.tld
ErrorLog /home/user.tld/log/error.log
CustomLog /home/user.tld/log/access.log combined
DocumentRoot /home/user.tld/html/sub/
</VirtualHost>
<Directory "/home/user.tld/html/sub/">
Order allow,deny
Allow from all
</Directory>

Домен + поддомен в NGINX

#Домен
server {
    listen       *:80;
    server_name user.tld www.user.tld; ## localhost;
    charset utf8;
    access_log /home/user.tldlog/access.log main;
    location / {
        proxy_pass http://user.tld:8080;
        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;
    }
    location ~* \.(jpg|jpeg|gif|png|ico|css|bmp|swf|js|html|txt)$ {
        root /home/user.tld/html/;
        access_log off;
        expires 30d;
    }
error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    location ~ /\.ht {
        deny  all;
    }
}

#Поддомен
server {
        listen *:80;
        server_name sub.user.tld www.sub.user.tld;
    location / {
       ## index  index.php index.html index.htm;
        proxy_pass http://sub.user.tld:8080;
        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;
    }
    location ~* \.(jpg|jpeg|gif|png|ico|css|bmp|swf|js|html|txt)$ {
        root /home/sub.user.tld/html/;
        access_log off;
        expires 30d;
    }
}


Для динамических поддоменов (в этом случае апач будет искать поддомен в user.tld/sites/)
т.е. в апаче не нужно создавать VirtualHost, но и владелец всех поддоменов будет user.tld
server {
    server_name   ~^(?<dynamic>[a-z0-9\-]+)\.user.tld$;
    location / {
        proxy_pass user.tld:80/sites/$dynamic$uri$is_args$args;
    }
}


В итоге получили два сайта, user.tld и sub.user.tld, управляемых разными пользователями user.tld и sub.user.tld в первом варианте, и одним пользователем - во втором.

четверг, 24 ноября 2016 г.