├── add_domain_nginx.sh └── README.md /add_domain_nginx.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | set -e 3 | 4 | command_exists() { 5 | command -v "$1" >/dev/null 2>&1 6 | } 7 | 8 | # Função para pedir entrada obrigatória com default 9 | read_required() { 10 | local PROMPT="$1" 11 | local DEFAULT="$2" 12 | local VAR 13 | while true; do 14 | if [ -n "$DEFAULT" ]; then 15 | read -p "$PROMPT [$DEFAULT]: " VAR 16 | VAR="${VAR:-$DEFAULT}" 17 | else 18 | read -p "$PROMPT: " VAR 19 | fi 20 | if [ -n "$VAR" ]; then 21 | echo "$VAR" 22 | return 23 | else 24 | echo "❌ Valor não pode ser vazio. Tente novamente." 25 | fi 26 | done 27 | } 28 | 29 | # Função para ler IP válido 30 | read_ip() { 31 | local DEFAULT="$1" 32 | local VAR 33 | while true; do 34 | read -p "Digite o IP do backend [$DEFAULT]: " VAR 35 | VAR="${VAR:-$DEFAULT}" 36 | if [[ "$VAR" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then 37 | echo "$VAR" 38 | return 39 | else 40 | echo "❌ IP inválido. Tente novamente." 41 | fi 42 | done 43 | } 44 | 45 | # Função para ler porta válida 46 | read_port() { 47 | local DEFAULT="$1" 48 | local VAR 49 | while true; do 50 | read -p "Digite a porta do backend [$DEFAULT]: " VAR 51 | VAR="${VAR:-$DEFAULT}" 52 | if [[ "$VAR" =~ ^[0-9]+$ ]] && [ "$VAR" -ge 1 ] && [ "$VAR" -le 65535 ]; then 53 | echo "$VAR" 54 | return 55 | else 56 | echo "❌ Porta inválida. Tente novamente." 57 | fi 58 | done 59 | } 60 | 61 | # Verificações iniciais 62 | if ! command_exists nginx; then 63 | echo "Nginx não está instalado. Abortando." 64 | exit 1 65 | fi 66 | 67 | if ! command_exists certbot; then 68 | echo "Certbot não encontrado. Instalando..." 69 | sudo apt update 70 | sudo apt install -y certbot python3-certbot-nginx 71 | fi 72 | 73 | # Perguntas ao usuário 74 | DOMAIN=$(read_required "Digite o domínio (ex: exemplo.com)") 75 | NGINX_PORT=$(read_required "Digite a porta que o Nginx deve escutar" "80") 76 | BACKEND_IP=$(read_ip "127.0.0.1") 77 | BACKEND_PORT=$(read_port "5000") 78 | BACKEND="http://$BACKEND_IP:$BACKEND_PORT" 79 | 80 | # Caminho do arquivo de configuração 81 | CONF_FILE="/etc/nginx/sites-available/$DOMAIN" 82 | 83 | # Cria arquivo de configuração 84 | sudo tee "$CONF_FILE" > /dev/null <HTTPS" 110 | 111 | echo "Pronto!" 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🌐 Nginx Domain Configuration Script 2 | 3 | [![Shell Script](https://img.shields.io/badge/Shell-Script-4EAA25?style=for-the-badge&logo=gnu-bash&logoColor=white)](https://www.gnu.org/software/bash/) 4 | [![Nginx](https://img.shields.io/badge/nginx-%23009639.svg?style=for-the-badge&logo=nginx&logoColor=white)](https://nginx.org/) 5 | [![Let's Encrypt](https://img.shields.io/badge/Let's%20Encrypt-003A70?style=for-the-badge&logo=letsencrypt&logoColor=white)](https://letsencrypt.org/) 6 | 7 | Um script automatizado para configurar proxy reverso no Nginx com SSL automático via Let's Encrypt. 8 | 9 | *An automated script to configure Nginx reverse proxy with automatic SSL via Let's Encrypt.* 10 | 11 | --- 12 | 13 | ## 🇧🇷 Português 14 | 15 | ### 📋 Descrição 16 | 17 | Este script automatiza completamente a configuração de um novo domínio no Nginx, incluindo: 18 | 19 | - ✅ Configuração de proxy reverso 20 | - ✅ Configuração automática de SSL via Certbot/Let's Encrypt 21 | - ✅ Redirecionamento automático HTTP → HTTPS 22 | - ✅ Validação de entrada de dados 23 | - ✅ Verificação de dependências 24 | 25 | ### 🚀 Funcionalidades 26 | 27 | - **Configuração Interativa**: Interface amigável com valores padrão 28 | - **Validação de Dados**: Verificação de IP e porta válidos 29 | - **SSL Automático**: Configuração automática de certificados SSL 30 | - **Proxy Reverso**: Redirecionamento para aplicação backend 31 | - **Headers de Proxy**: Configuração adequada de headers HTTP 32 | 33 | ### 📦 Pré-requisitos 34 | 35 | - **Sistema Operacional**: Linux (Ubuntu/Debian recomendado) 36 | - **Privilégios**: Acesso sudo 37 | - **Software**: Nginx instalado 38 | - **DNS**: Domínio apontando para o servidor 39 | 40 | ### 🛠️ Instalação 41 | 42 | 1. **Clone ou baixe o script:** 43 | 44 | ```bash 45 | wget https://raw.githubusercontent.com/leolmcoelho/nginx-proxy-setup/main/add_domain_nginx.sh 46 | # ou 47 | curl -O https://raw.githubusercontent.com/leolmcoelho/nginx-proxy-setup/main/add_domain_nginx.sh 48 | ``` 49 | 50 | 2. **Torne o script executável:** 51 | 52 | ```bash 53 | chmod +x add_domain_nginx.sh 54 | ``` 55 | 56 | ### 🎯 Uso 57 | 58 | Execute o script com privilégios de administrador: 59 | 60 | ```bash 61 | sudo ./add_domain_nginx.sh 62 | ``` 63 | 64 | O script solicitará as seguintes informações: 65 | 66 | | Campo | Descrição | Padrão | Exemplo | 67 | |-------|-----------|---------|---------| 68 | | **Domínio** | Nome do domínio a configurar | - | `meusite.com` | 69 | | **Porta Nginx** | Porta que o Nginx escutará | `80` | `80`, `8080` | 70 | | **IP Backend** | IP da aplicação backend | `127.0.0.1` | `192.168.1.100` | 71 | | **Porta Backend** | Porta da aplicação backend | `5000` | `3000`, `8000` | 72 | 73 | ### 📁 Estrutura de Arquivos Criados 74 | 75 | ```text 76 | /etc/nginx/ 77 | ├── sites-available/ 78 | │ └── meudominio.com # Configuração do site 79 | └── sites-enabled/ 80 | └── meudominio.com # Link simbólico (site ativo) 81 | ``` 82 | 83 | ### 🔧 Exemplo de Configuração Gerada 84 | 85 | ```nginx 86 | server { 87 | listen 80; 88 | server_name meusite.com www.meusite.com; 89 | 90 | location / { 91 | proxy_pass http://127.0.0.1:5000; 92 | proxy_set_header Host $host; 93 | proxy_set_header X-Real-IP $remote_addr; 94 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 95 | proxy_set_header X-Forwarded-Proto $scheme; 96 | } 97 | } 98 | ``` 99 | 100 | ### 🔒 Configuração SSL 101 | 102 | O script configura automaticamente: 103 | 104 | - Certificados SSL via Let's Encrypt 105 | - Redirecionamento HTTP → HTTPS 106 | - Renovação automática de certificados 107 | 108 | ### ⚠️ Observações Importantes 109 | 110 | 1. **Email para SSL**: Edite o script e substitua `seu-email@dominio.com` pelo seu email real 111 | 2. **Firewall**: Certifique-se de que as portas 80 e 443 estão abertas 112 | 3. **DNS**: O domínio deve estar apontando para o IP do servidor antes da execução 113 | 114 | ### 🐛 Solução de Problemas 115 | 116 | #### Erro: "Nginx não está instalado" 117 | 118 | ```bash 119 | sudo apt update && sudo apt install nginx 120 | ``` 121 | 122 | #### Erro de certificado SSL 123 | 124 | - Verifique se o domínio está acessível externamente 125 | - Confirme que as portas 80 e 443 estão abertas 126 | 127 | #### Erro de permissão 128 | 129 | - Execute o script com `sudo` 130 | 131 | ### 📝 Arquivos de Log 132 | 133 | - **Nginx**: `/var/log/nginx/access.log` e `/var/log/nginx/error.log` 134 | - **Certbot**: `/var/log/letsencrypt/letsencrypt.log` 135 | 136 | --- 137 | 138 | ## 🇺🇸 English 139 | 140 | ### 📋 Description 141 | 142 | This script completely automates the configuration of a new domain in Nginx, including: 143 | 144 | - ✅ Reverse proxy configuration 145 | - ✅ Automatic SSL configuration via Certbot/Let's Encrypt 146 | - ✅ Automatic HTTP → HTTPS redirection 147 | - ✅ Input data validation 148 | - ✅ Dependency checking 149 | 150 | ### 🚀 Features 151 | 152 | - **Interactive Configuration**: User-friendly interface with default values 153 | - **Data Validation**: Valid IP and port verification 154 | - **Automatic SSL**: Automatic SSL certificate configuration 155 | - **Reverse Proxy**: Redirection to backend application 156 | - **Proxy Headers**: Proper HTTP headers configuration 157 | 158 | ### 📦 Prerequisites 159 | 160 | - **Operating System**: Linux (Ubuntu/Debian recommended) 161 | - **Privileges**: Sudo access 162 | - **Software**: Nginx installed 163 | - **DNS**: Domain pointing to the server 164 | 165 | ### 🛠️ Installation 166 | 167 | 1. **Clone or download the script:** 168 | 169 | ```bash 170 | wget https://raw.githubusercontent.com/leolmcoelho/nginx-proxy-setup/main/add_domain_nginx.sh 171 | # or 172 | curl -O https://raw.githubusercontent.com/leolmcoelho/nginx-proxy-setup/main/add_domain_nginx.sh 173 | ``` 174 | 175 | 2. **Make the script executable:** 176 | 177 | ```bash 178 | chmod +x add_domain_nginx.sh 179 | ``` 180 | 181 | ### 🎯 Usage 182 | 183 | Run the script with administrator privileges: 184 | 185 | ```bash 186 | sudo ./add_domain_nginx.sh 187 | ``` 188 | 189 | The script will request the following information: 190 | 191 | | Field | Description | Default | Example | 192 | |-------|-------------|---------|---------| 193 | | **Domain** | Domain name to configure | - | `mysite.com` | 194 | | **Nginx Port** | Port that Nginx will listen on | `80` | `80`, `8080` | 195 | | **Backend IP** | Backend application IP | `127.0.0.1` | `192.168.1.100` | 196 | | **Backend Port** | Backend application port | `5000` | `3000`, `8000` | 197 | 198 | ### 📁 Created File Structure 199 | 200 | ```text 201 | /etc/nginx/ 202 | ├── sites-available/ 203 | │ └── mydomain.com # Site configuration 204 | └── sites-enabled/ 205 | └── mydomain.com # Symbolic link (active site) 206 | ``` 207 | 208 | ### 🔧 Generated Configuration Example 209 | 210 | ```nginx 211 | server { 212 | listen 80; 213 | server_name mysite.com www.mysite.com; 214 | 215 | location / { 216 | proxy_pass http://127.0.0.1:5000; 217 | proxy_set_header Host $host; 218 | proxy_set_header X-Real-IP $remote_addr; 219 | proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 220 | proxy_set_header X-Forwarded-Proto $scheme; 221 | } 222 | } 223 | ``` 224 | 225 | ### 🔒 SSL Configuration 226 | 227 | The script automatically configures: 228 | 229 | - SSL certificates via Let's Encrypt 230 | - HTTP → HTTPS redirection 231 | - Automatic certificate renewal 232 | 233 | ### ⚠️ Important Notes 234 | 235 | 1. **SSL Email**: Edit the script and replace `your-email@domain.com` with your real email 236 | 2. **Firewall**: Make sure ports 80 and 443 are open 237 | 3. **DNS**: The domain must be pointing to the server IP before execution 238 | 239 | ### 🐛 Troubleshooting 240 | 241 | #### Error: "Nginx is not installed" 242 | 243 | ```bash 244 | sudo apt update && sudo apt install nginx 245 | ``` 246 | 247 | #### SSL certificate error 248 | 249 | - Check if the domain is accessible externally 250 | - Confirm that ports 80 and 443 are open 251 | 252 | #### Permission error 253 | 254 | - Run the script with `sudo` 255 | 256 | ### 📝 Log Files 257 | 258 | - **Nginx**: `/var/log/nginx/access.log` and `/var/log/nginx/error.log` 259 | - **Certbot**: `/var/log/letsencrypt/letsencrypt.log` 260 | 261 | --- 262 | 263 | ## 🤝 Contribuição / Contributing 264 | 265 | Contribuições são bem-vindas! Por favor, abra uma issue ou envie um pull request. 266 | 267 | *Contributions are welcome! Please open an issue or submit a pull request.* 268 | 269 | ## 📄 Licença / License 270 | 271 | Este projeto está sob a licença MIT. Veja o arquivo [LICENSE](LICENSE) para mais detalhes. 272 | 273 | *This project is under the MIT License. See the [LICENSE](LICENSE) file for more details.* 274 | 275 | --- 276 | 277 | **⭐ Se este script foi útil, considere dar uma estrela ao repositório!** 278 | 279 | **⭐ If this script was helpful, consider giving a star to the repository!** 280 | 281 | --------------------------------------------------------------------------------