# Vision Videoke Apache Subdirectory Deployment Guide

## 🎬 Complete Guide for Apache Subdirectory Installation

This comprehensive guide will walk you through deploying Vision Videoke in an Apache subdirectory without affecting your existing website. Perfect for adding the platform to an existing domain like `yoursite.com/music`.

---

## 📋 Table of Contents

1. [Prerequisites](#prerequisites)
2. [Quick Installation](#quick-installation)
3. [Manual Installation](#manual-installation)
4. [Configuration](#configuration)
5. [Deployment](#deployment)
6. [Testing](#testing)
7. [Management](#management)
8. [Troubleshooting](#troubleshooting)
9. [Security](#security)
10. [Performance Optimization](#performance-optimization)

---

## 🔧 Prerequisites

### System Requirements

**Minimum Requirements:**
- **OS**: Amazon Linux 2, CentOS 7+, RHEL 7+, Ubuntu 18.04+, Debian 9+
- **RAM**: 2GB minimum, 4GB recommended
- **Storage**: 10GB free space minimum
- **CPU**: 1 vCPU minimum, 2 vCPU recommended

**Software Requirements:**
- **Apache**: 2.4+ (already installed and configured)
- **Node.js**: 16+ (will be installed if not present)
- **npm**: 8+ (comes with Node.js)
- **PM2**: Latest (will be installed)
- **curl**: For health checks and downloads

### Existing Apache Setup

Your Apache server should already be:
- ✅ **Installed and running**
- ✅ **Serving your main website**
- ✅ **Configured with your domain**
- ✅ **Accessible from the internet**

### Required Apache Modules

The installer will enable these modules automatically:
- `mod_rewrite` - URL rewriting for React Router
- `mod_headers` - Security and CORS headers
- `mod_expires` - Static file caching
- `mod_deflate` - Gzip compression
- `mod_proxy` - API proxying to Node.js backend
- `mod_proxy_http` - HTTP proxy support

### API Keys Required

You'll need API keys for full functionality:
- **OpenAI API Key** - For AI lyric generation
- **Udio API Key** - For music generation
- **ElevenLabs API Key** - For voice cloning
- **Stripe Keys** (optional) - For payment processing

---

## 🚀 Quick Installation

### One-Command Installation

For the fastest setup, use our automated installer:

```bash
# Download and run the installer
curl -fsSL https://your-domain.com/apache-installer.sh | bash
```

Or download and run manually:

```bash
# Download the installer
wget https://your-domain.com/apache-installer.sh
chmod +x apache-installer.sh

# Run the installer
./apache-installer.sh
```

### Installation Process

The installer will:

1. **Welcome Screen** - Show banner and collect configuration
2. **System Check** - Verify Apache and system requirements
3. **Node.js Setup** - Install Node.js 18 and PM2 if needed
4. **Apache Configuration** - Configure subdirectory routing
5. **Application Setup** - Create directory structure and files
6. **Service Start** - Start the backend service with PM2
7. **Testing** - Verify installation and accessibility
8. **Success Screen** - Show access information and next steps

### Interactive Configuration

During installation, you'll be prompted for:

```
Enter your domain name (e.g., mysite.com): yoursite.com
Enter subdirectory name [music]: music
OpenAI API Key: sk-...
Udio API Key: udio_...
ElevenLabs API Key: el_...
Stripe Publishable Key (optional): pk_...
Stripe Secret Key (optional): sk_...
```

### Installation Time

- **Total Time**: 15-20 minutes
- **Download**: 2-3 minutes
- **Configuration**: 5-7 minutes
- **Installation**: 8-10 minutes

---

## 🔧 Manual Installation

If you prefer manual control or need to customize the installation:

### Step 1: System Preparation

```bash
# Update system packages
sudo yum update -y  # Amazon Linux/CentOS/RHEL
# OR
sudo apt update && sudo apt upgrade -y  # Ubuntu/Debian

# Install required packages
sudo yum install -y curl wget git  # Amazon Linux/CentOS/RHEL
# OR
sudo apt install -y curl wget git  # Ubuntu/Debian
```

### Step 2: Node.js Installation

```bash
# Install Node.js 18 (Amazon Linux/CentOS/RHEL)
curl -fsSL https://rpm.nodesource.com/setup_18.x | sudo bash -
sudo yum install -y nodejs

# Install Node.js 18 (Ubuntu/Debian)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs

# Install PM2 globally
sudo npm install -g pm2
```

### Step 3: Apache Configuration

```bash
# Run the Apache configuration script
./scripts/configure-apache.sh yoursite.com music
```

This script will:
- Enable required Apache modules
- Create subdirectory configuration
- Set up proxy rules for the API
- Configure security headers
- Create .htaccess file
- Test and reload Apache

### Step 4: Application Setup

```bash
# Create application directory
sudo mkdir -p /var/www/html/music
sudo chown apache:apache /var/www/html/music  # RHEL/CentOS
# OR
sudo chown www-data:www-data /var/www/html/music  # Ubuntu/Debian

# Create environment configuration
cp templates/env.subdirectory.template /var/www/html/music/.env

# Edit environment file
nano /var/www/html/music/.env
```

### Step 5: PM2 Configuration

```bash
# Copy PM2 configuration
cp config/ecosystem.subdirectory.config.js /var/www/html/music/ecosystem.config.js

# Edit configuration if needed
nano /var/www/html/music/ecosystem.config.js
```

---

## ⚙️ Configuration

### Environment Variables

Edit `/var/www/html/music/.env`:

```bash
# Application Configuration
NODE_ENV=production
PORT=3001

# Subdirectory Configuration
SUBDIRECTORY_PATH=/music
API_BASE_PATH=/music/api
PUBLIC_PATH=/music

# Domain Configuration
DOMAIN_NAME=yoursite.com
APP_URL=https://yoursite.com/music
API_URL=https://yoursite.com/music/api

# API Keys (REQUIRED)
REACT_APP_OPENAI_API_KEY=your_openai_api_key_here
OPENAI_API_KEY=your_openai_api_key_here
REACT_APP_UDIO_API_KEY=your_udio_api_key_here
UDIO_API_KEY=your_udio_api_key_here
REACT_APP_ELEVENLABS_API_KEY=your_elevenlabs_api_key_here
ELEVENLABS_API_KEY=your_elevenlabs_api_key_here

# Payment Processing (Optional)
REACT_APP_STRIPE_PUBLISHABLE_KEY=pk_live_your_stripe_key
STRIPE_SECRET_KEY=sk_live_your_stripe_secret

# Security
JWT_SECRET=your_jwt_secret_32_characters_minimum
ENCRYPTION_KEY=your_encryption_key_32_characters
SESSION_SECRET=your_session_secret

# File Storage
UPLOAD_DIR=/var/www/html/music/uploads
TEMP_DIR=/var/www/html/music/temp
MAX_FILE_SIZE=100MB

# CORS Configuration
CORS_ORIGIN=https://yoursite.com
CORS_CREDENTIALS=true

# Feature Flags
REACT_APP_ENABLE_VOICE_CLONING=true
REACT_APP_ENABLE_VIDEO_GENERATION=true
REACT_APP_ENABLE_PAYMENTS=true
```

### Apache Virtual Host Configuration

The installer creates `/etc/httpd/conf.d/visionvideoke-music.conf`:

```apache
# Vision Videoke Apache Configuration
<Directory "/var/www/html/music">
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
    
    # React Router support
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/music/api/
    RewriteRule ^(.*)$ /music/index.html [L,QSA]
    
    # Security headers
    Header always set X-Content-Type-Options nosniff
    Header always set X-Frame-Options DENY
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    
    # CORS headers
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
</Directory>

# API proxy to Node.js backend
<Location "/music/api">
    ProxyPreserveHost On
    ProxyPass http://127.0.0.1:3001/api
    ProxyPassReverse http://127.0.0.1:3001/api
</Location>

# Health check endpoint
<Location "/music/health">
    ProxyPass http://127.0.0.1:3001/health
    ProxyPassReverse http://127.0.0.1:3001/health
</Location>

# File upload with increased limits
<Location "/music/api/upload">
    LimitRequestBody 104857600  # 100MB
    ProxyTimeout 300
    ProxyPass http://127.0.0.1:3001/api/upload
    ProxyPassReverse http://127.0.0.1:3001/api/upload
</Location>

# Static file caching
<LocationMatch "/music/.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$">
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
    Header append Cache-Control "public, immutable"
</LocationMatch>

# Gzip compression
<Location "/music">
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
</Location>

# Block sensitive files
<LocationMatch "/music/(\.env|package\.json|ecosystem\.config\.js|\.git)">
    Require all denied
</LocationMatch>
```

### PM2 Ecosystem Configuration

The PM2 configuration at `/var/www/html/music/ecosystem.config.js`:

```javascript
module.exports = {
  apps: [{
    name: 'visionvideoke-music',
    script: 'server.js',
    cwd: '/var/www/html/music',
    instances: 'max',
    exec_mode: 'cluster',
    env: {
      NODE_ENV: 'production',
      PORT: 3001,
      SUBDIRECTORY_PATH: '/music',
      API_BASE_PATH: '/music/api',
      PUBLIC_PATH: '/music'
    },
    error_file: '/var/log/visionvideoke/error.log',
    out_file: '/var/log/visionvideoke/out.log',
    log_file: '/var/log/visionvideoke/combined.log',
    time: true,
    max_memory_restart: '1G',
    restart_delay: 4000,
    max_restarts: 10,
    min_uptime: '10s',
    env_file: '/var/www/html/music/.env'
  }]
};
```

---

## 🚀 Deployment

### Deploying Your Application

Once the infrastructure is set up, deploy your Vision Videoke application:

#### Method 1: Using the Deployment Script

```bash
# Copy your application source to the server
scp -r ./MusicPlatformWeb/ user@yourserver:/tmp/visionvideoke-source/

# Run the deployment script
./scripts/apache-deploy.sh music /tmp/visionvideoke-source
```

#### Method 2: Manual Deployment

```bash
# Navigate to application directory
cd /var/www/html/music

# Copy your application files
rsync -av /tmp/visionvideoke-source/ . --exclude=node_modules

# Install dependencies
npm ci --production=false

# Configure for subdirectory deployment
export REACT_APP_BASE_PATH="/music"
export PUBLIC_URL="/music"

# Build the application
npm run build

# Start with PM2
pm2 start ecosystem.config.js
pm2 save
```

### Build Configuration for Subdirectory

Update your `vite.config.js` for subdirectory deployment:

```javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  base: '/music/',  // Your subdirectory path
  build: {
    outDir: 'dist',
    sourcemap: false,
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom']
        }
      }
    }
  },
  server: {
    proxy: {
      '/music/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/music\/api/, '/api')
      }
    }
  }
})
```

### React Router Configuration

Update your router for subdirectory support:

```javascript
import { createBrowserRouter, RouterProvider } from 'react-router-dom';

const router = createBrowserRouter([
  {
    path: '/',
    element: <Layout />,
    children: [
      { index: true, element: <HomePage /> },
      { path: 'create', element: <CreatePage /> },
      { path: 'dashboard', element: <DashboardPage /> },
      // ... other routes
    ]
  }
], {
  basename: '/music'  // Your subdirectory path
});

function App() {
  return <RouterProvider router={router} />;
}
```

---

## 🧪 Testing

### Automated Testing

The installer includes automated tests:

```bash
# Run the status check script
./visionvideoke-status.sh
```

### Manual Testing

#### 1. Backend Health Check

```bash
# Test backend directly
curl http://localhost:3001/health

# Expected response: "healthy"
```

#### 2. API Endpoint Test

```bash
# Test API through Apache proxy
curl http://yoursite.com/music/api/status

# Expected response: JSON with status information
```

#### 3. Frontend Access Test

```bash
# Test frontend access
curl -I http://yoursite.com/music

# Expected response: HTTP 200 OK
```

#### 4. React Router Test

```bash
# Test React Router routing
curl http://yoursite.com/music/create

# Should return the main index.html (React handles routing)
```

### Browser Testing

1. **Homepage**: Visit `http://yoursite.com/music`
2. **Create Page**: Navigate to `http://yoursite.com/music/create`
3. **API Test**: Check browser console for any errors
4. **File Upload**: Test vision board upload functionality
5. **Responsive Design**: Test on mobile and desktop

### Performance Testing

```bash
# Test page load speed
curl -w "@curl-format.txt" -o /dev/null -s http://yoursite.com/music

# Test with compression
curl -H "Accept-Encoding: gzip" -I http://yoursite.com/music
```

---

## 🔧 Management

### Daily Operations

#### Check Application Status

```bash
# Quick status check
./visionvideoke-status.sh

# Detailed PM2 status
pm2 status
pm2 logs visionvideoke-music

# Apache status
sudo systemctl status httpd  # or apache2
```

#### Restart Services

```bash
# Restart application only
./visionvideoke-restart.sh

# Restart PM2 process
pm2 restart visionvideoke-music

# Restart Apache
sudo systemctl restart httpd  # or apache2
```

#### View Logs

```bash
# Application logs
pm2 logs visionvideoke-music

# Apache logs
sudo tail -f /var/log/httpd/error_log  # or /var/log/apache2/error.log

# Vision Videoke specific logs
tail -f /var/log/visionvideoke/combined.log
```

### Backup and Recovery

#### Create Backup

```bash
# Create application backup
./visionvideoke-backup.sh

# Manual backup
tar -czf backup-$(date +%Y%m%d).tar.gz -C /var/www/html/music . \
    --exclude=node_modules --exclude=temp --exclude=logs
```

#### Restore from Backup

```bash
# Stop application
pm2 stop visionvideoke-music

# Restore files
cd /var/www/html/music
tar -xzf /var/backups/visionvideoke/backup-music-20240101-120000.tar.gz

# Restart application
pm2 start ecosystem.config.js
```

### Updates and Maintenance

#### Update Application

```bash
# Deploy new version
./scripts/apache-deploy.sh music /path/to/new/source

# Or manual update
cd /var/www/html/music
git pull origin main  # if using git
npm ci
npm run build
pm2 restart visionvideoke-music
```

#### Update Dependencies

```bash
cd /var/www/html/music

# Update npm packages
npm update

# Update PM2
sudo npm update -g pm2

# Update Node.js (if needed)
# Follow Node.js update procedures for your OS
```

#### System Maintenance

```bash
# Clean old logs
find /var/log/visionvideoke -name "*.log" -mtime +7 -delete

# Clean old backups
find /var/backups/visionvideoke -name "backup-*.tar.gz" -mtime +30 -delete

# Clean npm cache
npm cache clean --force

# Clean PM2 logs
pm2 flush
```

---

## 🔍 Troubleshooting

### Common Issues

#### 1. Application Not Accessible

**Symptoms:**
- 404 error when accessing `/music`
- "This site can't be reached" error

**Solutions:**

```bash
# Check Apache status
sudo systemctl status httpd
sudo systemctl restart httpd

# Check Apache configuration
sudo httpd -t
sudo systemctl reload httpd

# Check if subdirectory exists
ls -la /var/www/html/music

# Check Apache error logs
sudo tail -f /var/log/httpd/error_log
```

#### 2. API Requests Failing

**Symptoms:**
- Frontend loads but API calls fail
- CORS errors in browser console
- 502 Bad Gateway errors

**Solutions:**

```bash
# Check backend status
curl http://localhost:3001/health
pm2 status
pm2 logs visionvideoke-music

# Check proxy configuration
grep -A 10 "Location.*api" /etc/httpd/conf.d/visionvideoke-music.conf

# Restart backend
pm2 restart visionvideoke-music
```

#### 3. File Upload Issues

**Symptoms:**
- File uploads fail or timeout
- "Request Entity Too Large" errors

**Solutions:**

```bash
# Check upload limits in Apache config
grep -i "LimitRequestBody" /etc/httpd/conf.d/visionvideoke-music.conf

# Check disk space
df -h /var/www/html/music

# Check upload directory permissions
ls -la /var/www/html/music/uploads
sudo chown -R apache:apache /var/www/html/music/uploads
```

#### 4. React Router Issues

**Symptoms:**
- Direct URLs return 404
- Page refresh breaks the application
- Routes not working

**Solutions:**

```bash
# Check .htaccess file
cat /var/www/html/music/.htaccess

# Verify mod_rewrite is enabled
httpd -M | grep rewrite

# Check React Router basename
grep -r "basename" /var/www/html/music/src/
```

#### 5. Performance Issues

**Symptoms:**
- Slow page loads
- High server resource usage
- Timeouts

**Solutions:**

```bash
# Check server resources
top
free -h
df -h

# Check PM2 cluster status
pm2 status
pm2 monit

# Optimize PM2 configuration
# Edit ecosystem.config.js to adjust instances and memory limits

# Check Apache performance
sudo systemctl status httpd
```

### Debugging Commands

#### System Information

```bash
# System overview
uname -a
cat /etc/os-release
free -h
df -h

# Apache information
httpd -v
httpd -M | head -20

# Node.js information
node --version
npm --version
pm2 --version
```

#### Network Diagnostics

```bash
# Check port availability
netstat -tlnp | grep :3001
netstat -tlnp | grep :80

# Test local connectivity
curl -I http://localhost:3001/health
curl -I http://localhost/music

# Test external connectivity
curl -I http://yoursite.com/music
```

#### Log Analysis

```bash
# Apache error logs
sudo tail -f /var/log/httpd/error_log | grep music

# Apache access logs
sudo tail -f /var/log/httpd/access_log | grep music

# Application logs
tail -f /var/log/visionvideoke/combined.log

# System logs
sudo journalctl -u httpd -f
sudo journalctl -u pm2-ec2-user -f
```

### Getting Help

If you encounter issues not covered here:

1. **Check the logs** first - most issues are logged
2. **Verify configuration** - ensure all files are correctly configured
3. **Test components individually** - isolate the problem
4. **Check permissions** - many issues are permission-related
5. **Review recent changes** - what changed before the issue started?

---

## 🔒 Security

### Security Hardening

#### 1. File Permissions

```bash
# Set proper ownership
sudo chown -R apache:apache /var/www/html/music
sudo chown ec2-user:ec2-user /var/log/visionvideoke

# Set secure permissions
chmod 755 /var/www/html/music
chmod 644 /var/www/html/music/.env
chmod 600 /var/www/html/music/.env
find /var/www/html/music -type f -name "*.js" -exec chmod 644 {} \;
find /var/www/html/music -type d -exec chmod 755 {} \;
```

#### 2. Environment Security

```bash
# Secure environment file
chmod 600 /var/www/html/music/.env
chown apache:apache /var/www/html/music/.env

# Remove example files
rm -f /var/www/html/music/.env.example
rm -f /var/www/html/music/.env.local
```

#### 3. Apache Security Headers

The configuration includes security headers:

```apache
# Security headers
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" env=HTTPS

# Block sensitive files
<LocationMatch "/music/(\.env|package\.json|ecosystem\.config\.js|\.git)">
    Require all denied
</LocationMatch>
```

#### 4. Rate Limiting

Install and configure mod_evasive:

```bash
# Install mod_evasive (CentOS/RHEL)
sudo yum install -y mod_evasive

# Install mod_evasive (Ubuntu/Debian)
sudo apt install -y libapache2-mod-evasive

# Configure in Apache
echo "
<IfModule mod_evasive24.c>
    <Location \"/music/api\">
        DOSHashTableSize    2048
        DOSPageCount        10
        DOSPageInterval     1
        DOSSiteCount        50
        DOSSiteInterval     1
        DOSBlockingPeriod   600
    </Location>
</IfModule>
" | sudo tee -a /etc/httpd/conf.d/visionvideoke-music.conf
```

#### 5. SSL/TLS Configuration

For production, enable HTTPS:

```bash
# Install Certbot
sudo yum install -y certbot python3-certbot-apache

# Get SSL certificate
sudo certbot --apache -d yoursite.com

# Auto-renewal
echo "0 12 * * * /usr/bin/certbot renew --quiet" | sudo crontab -
```

### Monitoring and Alerting

#### 1. Health Monitoring

Create a monitoring script:

```bash
#!/bin/bash
# /home/ec2-user/monitor-visionvideoke.sh

SUBDIRECTORY="music"
BACKEND_PORT="3001"
DOMAIN="yoursite.com"

# Check backend health
if ! curl -f -s http://localhost:$BACKEND_PORT/health > /dev/null; then
    echo "ALERT: Backend health check failed" | mail -s "VisionVideoke Alert" admin@yoursite.com
fi

# Check frontend access
if ! curl -f -s http://$DOMAIN/$SUBDIRECTORY > /dev/null; then
    echo "ALERT: Frontend access failed" | mail -s "VisionVideoke Alert" admin@yoursite.com
fi

# Check disk space
DISK_USAGE=$(df /var/www/html/$SUBDIRECTORY | awk 'NR==2 {print $5}' | sed 's/%//')
if [ $DISK_USAGE -gt 80 ]; then
    echo "ALERT: Disk usage is ${DISK_USAGE}%" | mail -s "VisionVideoke Alert" admin@yoursite.com
fi
```

#### 2. Log Monitoring

Set up log rotation:

```bash
# Create logrotate configuration
sudo tee /etc/logrotate.d/visionvideoke <<EOF
/var/log/visionvideoke/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 644 ec2-user ec2-user
    postrotate
        pm2 reloadLogs
    endscript
}
EOF
```

#### 3. Automated Backups

Set up automated backups:

```bash
# Create backup script
cat > /home/ec2-user/backup-visionvideoke.sh <<'EOF'
#!/bin/bash
BACKUP_DIR="/var/backups/visionvideoke"
APP_DIR="/var/www/html/music"
DATE=$(date +%Y%m%d-%H%M%S)

mkdir -p $BACKUP_DIR

# Create backup
tar -czf "$BACKUP_DIR/backup-music-$DATE.tar.gz" \
    -C "$APP_DIR" . \
    --exclude=node_modules \
    --exclude=temp \
    --exclude=logs \
    --exclude=uploads

# Keep only last 30 backups
cd $BACKUP_DIR
ls -t backup-music-*.tar.gz | tail -n +31 | xargs rm -f
EOF

chmod +x /home/ec2-user/backup-visionvideoke.sh

# Add to crontab (daily at 2 AM)
echo "0 2 * * * /home/ec2-user/backup-visionvideoke.sh" | crontab -
```

---

## ⚡ Performance Optimization

### Apache Optimization

#### 1. Enable Compression

```apache
# Add to Apache configuration
<Location "/music">
    SetOutputFilter DEFLATE
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png)$ no-gzip dont-vary
    SetEnvIfNoCase Request_URI \
        \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
</Location>
```

#### 2. Static File Caching

```apache
# Cache static assets
<LocationMatch "/music/.*\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$">
    ExpiresActive On
    ExpiresDefault "access plus 1 year"
    Header append Cache-Control "public, immutable"
</LocationMatch>

# Cache HTML files briefly
<LocationMatch "/music/.*\.html$">
    ExpiresActive On
    ExpiresDefault "access plus 1 hour"
    Header append Cache-Control "public, must-revalidate"
</LocationMatch>
```

#### 3. Connection Optimization

```apache
# Add to main Apache configuration
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

# Enable HTTP/2 if available
LoadModule http2_module modules/mod_http2.so
Protocols h2 http/1.1
```

### Node.js Optimization

#### 1. PM2 Cluster Mode

```javascript
// ecosystem.config.js optimization
module.exports = {
  apps: [{
    name: 'visionvideoke-music',
    script: 'server.js',
    instances: 'max',  // Use all CPU cores
    exec_mode: 'cluster',
    max_memory_restart: '1G',
    node_args: '--max-old-space-size=1024',
    
    // Performance settings
    restart_delay: 4000,
    max_restarts: 10,
    min_uptime: '10s',
    
    // Monitoring
    monitoring: false,  // Disable if not needed
    pmx: false
  }]
};
```

#### 2. Application Optimization

```javascript
// server.js optimizations
const express = require('express');
const compression = require('compression');
const helmet = require('helmet');

const app = express();

// Enable compression
app.use(compression());

// Security headers
app.use(helmet({
  contentSecurityPolicy: false  // Adjust as needed
}));

// Static file serving with caching
app.use(express.static('dist', {
  maxAge: '1y',  // Cache for 1 year
  etag: true,
  lastModified: true
}));
```

### Database Optimization

If using a database:

#### 1. Connection Pooling

```javascript
// Database connection optimization
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 20,  // Maximum connections
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});
```

#### 2. Query Optimization

```javascript
// Use prepared statements
const query = 'SELECT * FROM songs WHERE user_id = $1';
const values = [userId];
const result = await pool.query(query, values);
```

### Frontend Optimization

#### 1. Build Optimization

```javascript
// vite.config.js optimization
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom'],
          ui: ['framer-motion', '@heroicons/react']
        }
      }
    },
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  }
});
```

#### 2. Code Splitting

```javascript
// Lazy load components
import { lazy, Suspense } from 'react';

const CreatePage = lazy(() => import('./pages/CreatePage'));
const DashboardPage = lazy(() => import('./pages/DashboardPage'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/create" element={<CreatePage />} />
        <Route path="/dashboard" element={<DashboardPage />} />
      </Routes>
    </Suspense>
  );
}
```

### Monitoring Performance

#### 1. Application Metrics

```bash
# Monitor with PM2
pm2 monit

# Check memory usage
pm2 show visionvideoke-music

# View performance logs
pm2 logs visionvideoke-music --lines 100
```

#### 2. Apache Metrics

```bash
# Enable Apache status module
echo "
<Location \"/server-status\">
    SetHandler server-status
    Require local
</Location>
" | sudo tee -a /etc/httpd/conf/httpd.conf

# View status
curl http://localhost/server-status
```

#### 3. System Metrics

```bash
# CPU and memory usage
top
htop  # if installed

# Disk I/O
iotop  # if installed

# Network usage
iftop  # if installed
```

---

## 📞 Support and Maintenance

### Regular Maintenance Tasks

#### Daily
- Check application status
- Monitor error logs
- Verify backup completion

#### Weekly
- Review performance metrics
- Clean old log files
- Update security patches

#### Monthly
- Update dependencies
- Review and optimize configuration
- Test backup restoration
- Security audit

### Support Resources

- **Documentation**: This guide and included README files
- **Logs**: `/var/log/visionvideoke/` and Apache logs
- **Configuration**: All config files are documented
- **Scripts**: Management scripts for common tasks

### Upgrade Path

When new versions are available:

1. **Backup current installation**
2. **Test new version in staging**
3. **Deploy using the deployment script**
4. **Verify functionality**
5. **Monitor for issues**

---

This completes the comprehensive Apache deployment guide for Vision Videoke. The platform is designed to run seamlessly alongside your existing Apache website while providing a professional music video creation service in a subdirectory.

