# 🚀 Deploy Tunnel SaaS v2 ke Nginx (VPS / Plesk / aapanel)

Panduan deploy ke server **Nginx** sebagai alternatif Apache/cPanel.

> **Catatan**: Project ini support Apache (`.htaccess`) **dan** Nginx (config block). Setiap folder sudah ada `nginx.conf.example` siap pakai.

---

## 📋 Sebelum Mulai

Pastikan punya:
- ✅ VPS dengan Nginx + PHP-FPM (atau hosting Nginx managed)
- ✅ SSH access atau panel hosting yang punya "Additional Nginx directives"
- ✅ Domain + subdomain DNS sudah point ke IP server

---

## 🗺️ Struktur Target

```
/var/www/tunnel-saas/
├── server/      → subdomain api.mydomain.com
├── admin/       → subdomain manage.mydomain.com (atau /manage/)
└── client/      (tidak dipasang di server pusat — ini template untuk owner client)
```

---

## ⚡ Setup 4 Step di VPS Nginx

### Step 1: Upload Files

Pakai SCP atau Git:

```bash
# Via Git (kalau project di repo)
cd /var/www
git clone https://github.com/yourrepo/tunnel-saas.git

# Atau via SCP dari lokal
scp -r tunnel-saas/ user@vps:/var/www/
```

Set permission:
```bash
sudo chown -R www-data:www-data /var/www/tunnel-saas
sudo chmod -R 755 /var/www/tunnel-saas
sudo chmod -R 775 /var/www/tunnel-saas/server/cache/
sudo chmod -R 775 /var/www/tunnel-saas/admin/data/
```

### Step 2: Setup Nginx Server Pusat

```bash
sudo cp /var/www/tunnel-saas/server/nginx.conf.example /etc/nginx/sites-available/api.mydomain.com
sudo nano /etc/nginx/sites-available/api.mydomain.com
```

Edit:
- `server_name` → `api.mydomain.com`
- `root` → `/var/www/tunnel-saas/server`
- `fastcgi_pass` → cek versi PHP-FPM Anda:
  ```bash
  ls /run/php/
  # Output: php8.1-fpm.sock (atau php8.2-fpm.sock, dst)
  ```

Aktifkan + reload:
```bash
sudo ln -s /etc/nginx/sites-available/api.mydomain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

### Step 3: Setup Nginx Admin Panel

```bash
sudo cp /var/www/tunnel-saas/admin/nginx.conf.example /etc/nginx/sites-available/manage.mydomain.com
sudo nano /etc/nginx/sites-available/manage.mydomain.com
```

Edit `server_name`, `root`, `fastcgi_pass`.

Aktifkan:
```bash
sudo ln -s /etc/nginx/sites-available/manage.mydomain.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

### Step 4: SSL via Let's Encrypt

```bash
sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d api.mydomain.com -d manage.mydomain.com
```

Certbot otomatis edit config Nginx + redirect HTTP → HTTPS.

---

## 🎛️ Setup di Panel Hosting (Plesk / aapanel / Cyberpanel)

Kalau tidak punya SSH dan pakai panel hosting Nginx:

### Plesk Nginx
1. Plesk → Subscription → Apache & Nginx Settings
2. Field "Additional Nginx directives"
3. Paste isi `server/nginx.conf.example` (hanya isi dalam `server { }`, tanpa server block luar)
4. OK → reload otomatis

### aapanel
1. aapanel → Website → klik domain api.mydomain.com
2. "Config File" → Edit langsung
3. Tambahkan location/rewrite block dari `nginx.conf.example`
4. Save → reload otomatis

### Cyberpanel
1. Websites → List Websites → klik domain
2. Rewrite Rules → tambahkan
3. Atau Manage → "vHost Conf" untuk edit langsung

---

## 🩺 Verifikasi

Setelah deploy:

```bash
# Test server endpoint
curl https://api.mydomain.com/render.php
# Expected: "Invalid API key"

# Test admin login
curl -I https://manage.mydomain.com/
# Expected: 200 OK
```

Login admin → klik **🩺 System Check** → semua harus hijau.

---

## 🌐 Untuk Owner Client (Nginx Hosting)

Saat Anda generate ZIP via admin → **📦 Download Client Files**, file ZIP berisi:

```
tunnel-client-XXX.zip
├── main-domain/
│   ├── index.php                  ← wajib upload
│   ├── .htaccess                  ← untuk Apache
│   ├── nginx.conf.example         ← untuk Nginx
│   └── README.txt                 ← panduan keduanya
└── amp-domain/                    (sama, untuk AMP)
```

**Owner client dengan Nginx hosting**:
1. Upload **hanya** `index.php` (skip `.htaccess` karena diabaikan Nginx)
2. Buka `nginx.conf.example`, copy isinya
3. Pasang di panel hosting mereka (Plesk/aapanel/dll) di "Additional Nginx directives"
4. Sesuaikan `server_name` & PHP version socket
5. Reload Nginx

---

## ⚙️ Tips Performa Nginx

### Enable OPcache
```bash
sudo nano /etc/php/8.1/fpm/conf.d/10-opcache.ini
```
```ini
opcache.enable=1
opcache.memory_consumption=128
opcache.max_accelerated_files=10000
opcache.validate_timestamps=1
opcache.revalidate_freq=2
```

### Tune PHP-FPM Pool
```bash
sudo nano /etc/php/8.1/fpm/pool.d/www.conf
```
```ini
pm = dynamic
pm.max_children = 50
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 15
pm.max_requests = 500
```

### Enable Gzip
Di nginx.conf utama:
```nginx
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml application/json application/javascript application/xml+rss;
```

### Cache Banner Images
Sudah otomatis via `location ~* \.(png|jpg|...)$` di nginx.conf.example.

---

## 🛡️ Security Hardening Nginx

### Block file sensitif (sudah di nginx.conf.example)
```nginx
location ~ ^/(saas_config\.php|config\.php|list\.txt|seeds\.txt)$ {
    deny all;
}
location ~ /\.(ht|env|git) {
    deny all;
}
```

### Rate limiting (opsional, anti-brute force)
Di nginx.conf utama (http block):
```nginx
limit_req_zone $binary_remote_addr zone=admin:10m rate=10r/m;
```

Di server block admin:
```nginx
location ~ /login {
    limit_req zone=admin burst=5;
}
```

### Hide Nginx version
```nginx
server_tokens off;
```

### HSTS (force HTTPS forever)
```nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
```

---

## 🔄 Update Template Tanpa Downtime

```bash
# Pull update dari git
cd /var/www/tunnel-saas
sudo -u www-data git pull

# Atau upload file baru via SCP
# (tidak perlu reload Nginx karena hanya file PHP yang berubah)

# OPcache reset (kalau enable validate_timestamps=0):
sudo systemctl reload php8.1-fpm
```

---

## 🆘 Troubleshooting Nginx

| Problem | Solusi |
|---|---|
| 404 di semua URL bersih | Cek `try_files $uri $uri/ /index.php?$query_string;` di config |
| 500 Internal Server Error | `tail /var/log/nginx/error.log` + `tail /var/log/php8.1-fpm.log` |
| 502 Bad Gateway | PHP-FPM tidak jalan: `sudo systemctl restart php8.1-fpm` |
| 504 Gateway Timeout | Naikkan `fastcgi_read_timeout` di config |
| Banner image 404 | Cek `location ~ \.png$` mengizinkan akses dinamis ke `/img/` rewrite |
| Admin login muter | Cek folder session PHP writable + cookie domain |

---

## 📊 Apache vs Nginx Comparison

| Aspek | Apache | Nginx |
|---|---|---|
| Config | `.htaccess` (per folder) | `server { }` block (global) |
| Plug-and-play | ✅ Drop file, jalan | ❌ Harus edit config + reload |
| Performance | Slower under load | Faster, more efficient |
| Memory usage | Lebih boros | Lebih hemat |
| Setup complexity | Mudah (shared hosting) | Butuh sedikit pengetahuan |
| Hot reload | ✅ Otomatis | Harus `nginx -s reload` |
| Best for | Shared hosting cPanel | VPS, traffic tinggi |

Project ini support keduanya, pilih sesuai infrastruktur Anda.

---

## 📁 File Nginx Config yang Tersedia

```
tunnel-saas/
├── server/nginx.conf.example      ← untuk server pusat
├── admin/nginx.conf.example       ← untuk admin panel
└── client/nginx.conf.example      ← untuk owner client (template)

ZIP yang di-generate dari admin:
└── tunnel-client-XXX.zip
    ├── main-domain/nginx.conf.example    ← auto-disesuaikan dgn domain client
    └── amp-domain/nginx.conf.example     ← auto-disesuaikan amp.{client}
```

---

📘 **Untuk shared hosting Apache (cPanel)**: lihat [`DEPLOY-CPANEL.txt`](DEPLOY-CPANEL.txt)
📘 **Quick deploy 7-step**: lihat [`QUICK-DEPLOY.md`](QUICK-DEPLOY.md)
📘 **Arsitektur lengkap**: lihat [`README.txt`](README.txt)
