Nginx habilitar o comando do site

107

Todos nós sabemos como ativar um site usando o apache no linux. Tenho certeza de que todos concordamos em usar o comando a2ensite.

Infelizmente não existe um comando padrão equivalente vem com o Nginx, mas aconteceu que eu instalei algum pacote no Ubuntu que me permitiu ativar / desativar sites e listá-los.

O problema é que não lembro o nome deste pacote.

Alguém sabe do que estou falando?

Por favor, me diga o nome deste pacote e o nome do comando.

    
por Ghassen Telmoudi 05.09.2012 / 10:33

5 respostas

59

Basta criar este script /usr/bin/nginx_modsite e torná-lo executável.

#!/bin/bash

##
#  File:
#    nginx_modsite
#  Description:
#    Provides a basic script to automate enabling and disabling websites found
#    in the default configuration directories:
#      /etc/nginx/sites-available and /etc/nginx/sites-enabled
#    For easy access to this script, copy it into the directory:
#      /usr/local/sbin
#    Run this script without any arguments or with -h or --help to see a basic
#    help dialog displaying all options.
##

# Copyright (C) 2010 Michael Lustfield <[email protected]>

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ''AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

##
# Default Settings
##

NGINX_CONF_FILE="$(awk -F= -v RS=' ' '/conf-path/ {print $2}' <<< $(nginx -V 2>&1))"
NGINX_CONF_DIR="${NGINX_CONF_FILE%/*}"
NGINX_SITES_AVAILABLE="$NGINX_CONF_DIR/sites-available"
NGINX_SITES_ENABLED="$NGINX_CONF_DIR/sites-enabled"
SELECTED_SITE="$2"

##
# Script Functions
##

ngx_enable_site() {
    [[ ! "$SELECTED_SITE" ]] &&
        ngx_select_site "not_enabled"

    [[ ! -e "$NGINX_SITES_AVAILABLE/$SELECTED_SITE" ]] && 
        ngx_error "Site does not appear to exist."
    [[ -e "$NGINX_SITES_ENABLED/$SELECTED_SITE" ]] &&
        ngx_error "Site appears to already be enabled"

    ln -sf "$NGINX_SITES_AVAILABLE/$SELECTED_SITE" -T "$NGINX_SITES_ENABLED/$SELECTED_SITE"
    ngx_reload
}

ngx_disable_site() {
    [[ ! "$SELECTED_SITE" ]] &&
        ngx_select_site "is_enabled"

    [[ ! -e "$NGINX_SITES_AVAILABLE/$SELECTED_SITE" ]] &&
        ngx_error "Site does not appear to be \'available\'. - Not Removing"
    [[ ! -e "$NGINX_SITES_ENABLED/$SELECTED_SITE" ]] &&
        ngx_error "Site does not appear to be enabled."

    rm -f "$NGINX_SITES_ENABLED/$SELECTED_SITE"
    ngx_reload
}

ngx_list_site() {
    echo "Available sites:"
    ngx_sites "available"
    echo "Enabled Sites"
    ngx_sites "enabled"
}

##
# Helper Functions
##

ngx_select_site() {
    sites_avail=($NGINX_SITES_AVAILABLE/*)
    sa="${sites_avail[@]##*/}"
    sites_en=($NGINX_SITES_ENABLED/*)
    se="${sites_en[@]##*/}"

    case "$1" in
        not_enabled) sites=$(comm -13 <(printf "%s\n" $se) <(printf "%s\n" $sa));;
        is_enabled) sites=$(comm -12 <(printf "%s\n" $se) <(printf "%s\n" $sa));;
    esac

    ngx_prompt "$sites"
}

ngx_prompt() {
    sites=($1)
    i=0

    echo "SELECT A WEBSITE:"
    for site in ${sites[@]}; do
        echo -e "$i:\t${sites[$i]}"
        ((i++))
    done

    read -p "Enter number for website: " i
    SELECTED_SITE="${sites[$i]}"
}

ngx_sites() {
    case "$1" in
        available) dir="$NGINX_SITES_AVAILABLE";;
        enabled) dir="$NGINX_SITES_ENABLED";;
    esac

    for file in $dir/*; do
        echo -e "\t${file#*$dir/}"
    done
}

ngx_reload() {
    read -p "Would you like to reload the Nginx configuration now? (Y/n) " reload
    [[ "$reload" != "n" && "$reload" != "N" ]] && invoke-rc.d nginx reload
}

ngx_error() {
    echo -e "${0##*/}: ERROR: $1"
    [[ "$2" ]] && ngx_help
    exit 1
}

ngx_help() {
    echo "Usage: ${0##*/} [options]"
    echo "Options:"
    echo -e "\t<-e|--enable> <site>\tEnable site"
    echo -e "\t<-d|--disable> <site>\tDisable site"
    echo -e "\t<-l|--list>\t\tList sites"
    echo -e "\t<-h|--help>\t\tDisplay help"
    echo -e "\n\tIf <site> is left out a selection of options will be presented."
    echo -e "\tIt is assumed you are using the default sites-enabled and"
    echo -e "\tsites-disabled located at $NGINX_CONF_DIR."
}

##
# Core Piece
##

case "$1" in
    -e|--enable)    ngx_enable_site;;
    -d|--disable)   ngx_disable_site;;
    -l|--list)  ngx_list_site;;
    -h|--help)  ngx_help;;
    *)      ngx_error "No Options Selected" 1; ngx_help;;
esac

Como funciona:

Para listar todos os sites

$ sudo nginx_modsite -l

Para ativar o site "test_website"

$ sudo nginx_modsite -e test_website

Para desativar o site "test_website"

$ sudo nginx_modsite -d test_website
    
por 18.12.2013 / 15:58
133

Se você instalou o pacote nginx dos repositórios do Ubuntu, você terá dois diretórios.

/etc/nginx/sites-enabled e /etc/nginx/sites-available .

Na configuração principal do nginx, /etc/nginx/nginx.conf , você tem a seguinte linha:

include /etc/nginx/sites-enabled/*.conf;

Então, basicamente, para listar todos os virtualhosts disponíveis, você pode executar o seguinte comando:

ls /etc/nginx/sites-available

Para ativar um deles, execute o seguinte comando:

ln -s /etc/nginx/sites-available/www.example.org.conf /etc/nginx/sites-enabled/

Os scripts que vêm com o Apache são basicamente simples invólucros de shell que fazem algo semelhante ao anterior.

Após vincular os arquivos, lembre-se de executar sudo service nginx reload / service nginx reload

    
por 05.09.2012 / 10:49
30

Você está se referindo a nginx_ensite e nginx_dissite ?

    
por 05.09.2012 / 10:36
2

NGINX

Se você estiver usando um dos pacotes oficiais de upstream do nginx de link , a melhor maneira é navegar para o diretório /etc/nginx/conf.d e renomear o arquivo afetado de ter um sufixo .conf para um diferente para desativar o site :

sudo mv -i /etc/nginx/conf.d/default.conf{,.off}

Ou o contrário para ativá-lo:

sudo mv -i /etc/nginx/conf.d/example.com.conf{.disabled,}

Isso ocorre porque o /etc/nginx/nginx.conf padrão tem a seguinte diretiva include :

http {
    …
    include /etc/nginx/conf.d/*.conf;
}

Debian / Ubuntu

No entanto, se você estiver usando um derivado Debian / Ubuntu, além de conf.d , você também pode ter o mal não-padrão sites-available e sites-enabled diretórios, alguns arquivos sob os quais podem ser incluídos sem considerar sua extensão:

http {
    …
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Como tal, no Debian / Ubuntu, você pode primeiro ter que descobrir onde a configuração do site está localizada.

  • Você pode usar o seguinte comando para obter uma lista de todos os sites disponíveis executando find(1) para encontrar todos os arquivos regulares que correspondem à máscara fornecida:

    find /etc/nginx -maxdepth 2 -type f \( -path "*/conf.d/*.conf" -or -path "*/sites-*/*" \)

  • Você pode usar o seguinte comando para obter uma lista de todos os sites enabled :

    find /etc/nginx -maxdepth 2 \( -path "*/conf.d/*.conf" -or -path "*/sites-enabled/*" \)

Então, para desativar / ativar sites no Debian / Ubuntu:

  • Para desativar um site: se a configuração estiver em conf.d , basta renomear o arquivo para não mais ter um sufixo .conf ; ou se em sites-enabled , mova-o para fora de sites-enabled .

  • Para ativar um site, a melhor maneira seria movê-lo para /etc/nginx/conf.d e renomear para ter um sufixo .conf .

P.S. Por que eu acho que o include /etc/nginx/sites-enabled/*; do Debian é ruim? Tente editar alguns arquivos nesse diretório e faça com que seus emacs criem os arquivos de backup (com o sufixo ~ ) , então me pergunte novamente.

    
por 26.08.2017 / 22:45
0

Outro método é apenas renomear o arquivo de configuração do site para algo que termina sem o .conf

Por exemplo sudo mv mysite.conf mysite.conf.disabled

Em seguida, recarregue o nginx e esse vhost retornará ao padrão.

    
por 19.05.2015 / 05:15