yobuild/htaccess-generator

Enhanced .htaccess generator with comprehensive security, performance, and pretty URLs configuration

dev-main 2025-07-15 10:31 UTC

This package is auto-updated.

Last update: 2025-07-15 10:31:49 UTC


README

PHP Version License Composer

A comprehensive, security-focused .htaccess generator with advanced configuration options, pretty URLs support, and enterprise-level security features.

๐Ÿš€ Features

  • ๐Ÿ”’ Advanced Security: Content Security Policy, HSTS, XSS protection, rate limiting
  • โšก Performance Optimization: Gzip compression, browser caching, WebP support
  • ๐ŸŒ Pretty URLs: Multiple routing modes (front-controller, extension-removal, hybrid)
  • ๐Ÿ›ก๏ธ Access Control: IP blacklisting/whitelisting, country blocking, bot protection
  • โš™๏ธ Highly Configurable: PHP configuration files with validation
  • ๐Ÿ–ฅ๏ธ CLI Tool: Command-line interface with colored output and progress tracking
  • ๐Ÿ“ฑ Web Interface: Bootstrap-based form for visual configuration
  • ๐Ÿ”„ Multiple Formats: Support for various deployment scenarios

๐Ÿ“ฆ Installation

Via Composer (Recommended)

composer require yobuild/htaccess-generator

Manual Installation

git clone https://github.com/YoBuild/htaccess-generator.git
cd htaccess-generator

๐ŸŽฏ Quick Start

1. CLI Usage (Recommended)

# Using Composer
vendor/bin/generate-htaccess examples/simple-config.php .htaccess

# Using Composer scripts
composer run generate examples/simple-config.php .htaccess

# Manual usage
php bin/generate-htaccess examples/simple-config.php .htaccess

2. PHP Code Usage

<?php
require_once 'vendor/autoload.php';

use YoBuild\Generators\HtaccessGenerator;

$config = [
	'domain' => 'mywebsite.com',
	'force_https' => true,
	'security_headers' => true,
	'pretty_urls' => true,
	'pretty_urls_config' => [
		'handler_file' => 'index.php',
		'mode' => 'front-controller'
	]
];

$generator = new HtaccessGenerator($config);
$htaccessContent = $generator->generate();

// Save to file
$generator->saveToFile('.htaccess');

3. Web Interface Usage

  1. Open index.html in your web browser
  2. Configure options using the Bootstrap form interface
  3. Click "Generate .htaccess" to create your configuration
  4. Copy the generated content to your .htaccess file

๐Ÿ“‹ Configuration Options

Basic Configuration

return [
	'htaccess_config' => [
		// Essential settings
		'domain' => 'mywebsite.com',
		'force_https' => true,
		'security_headers' => true,
		'compression' => true,

		// CDN and CORS
		'cdn_domains' => ['cdn.mywebsite.com', 'assets.mywebsite.com'],
		'cors_domains' => ['api.mywebsite.com', 'app.mywebsite.com'],

		// Performance
		'enable_caching' => true,
		'cache_html_duration' => '1 week',
		'cache_images_duration' => '1 year',
		'use_webp' => true,

		// Security
		'block_bad_bots' => true,
		'request_rate_limiting' => true,
		'max_requests_per_second' => 15,
	]
];

Pretty URLs Configuration

The generator supports three routing modes for pretty URLs:

Front Controller (Most Common)

'pretty_urls' => true,
'pretty_urls_config' => [
	'handler_file' => 'index.php',
	'mode' => 'front-controller',
	'excluded_directories' => ['assets', 'css', 'js', 'images', 'uploads'],
	'url_parameter_name' => 'url' // $_GET['url'] contains the path
]

Generated Rewrite Rules:

RewriteCond %{REQUEST_URI} !^/(assets|css|js|images|uploads)(/.*)?$ [NC]
RewriteCond %{REQUEST_URI} !\.(css|js|png|jpg|jpeg|gif|ico|txt|xml|json)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

URL Examples:

  • /about โ†’ index.php?url=about
  • /blog/post-title โ†’ index.php?url=blog/post-title
  • /contact?message=hello โ†’ index.php?url=contact&message=hello

Extension Removal

'pretty_urls_config' => [
	'mode' => 'extension-removal' // Remove .php/.html extensions
]

Hybrid Mode

'pretty_urls_config' => [
	'mode' => 'both' // Combines front-controller and extension-removal
]

Security Configuration

'security_headers' => true,
'content_security_policy' => true,
'cors_headers' => true,
'block_bad_bots' => true,
'protect_sensitive_files' => true,
'file_upload_protection' => true,
'request_rate_limiting' => true,
'max_requests_per_second' => 10,

// IP Access Control
'ip_blacklist' => ['192.168.1.100', '10.0.0.0/8'],
'ip_whitelist' => ['203.0.113.50'], // Restrictive - only these IPs allowed
'country_blacklist' => ['CN', 'RU'], // Block by country (requires GeoIP)

// SSL/TLS Configuration
'ssl_requirements' => [
	'min_version' => 'TLSv1.3',
	'enforce_hsts' => true,
	'hsts_max_age' => 31536000,
	'include_subdomains' => true,
	'preload' => true
]

๐Ÿ“– Configuration Examples

Simple Website

return [
	'htaccess_config' => [
		'domain' => 'mywebsite.com',
		'force_https' => true,
		'security_headers' => true,
		'compression' => true,
		'www_redirection' => 'non-www'
	]
];

Modern Framework (Laravel/Symfony Style)

return [
	'htaccess_config' => [
		'domain' => 'myapp.com',
		'pretty_urls' => true,
		'pretty_urls_config' => [
			'handler_file' => 'public/index.php', // Framework structure
			'mode' => 'front-controller',
			'excluded_directories' => ['assets', 'vendor', 'storage'],
			'url_parameter_name' => 'pathinfo'
		],
		'force_https' => true,
		'security_headers' => true
	]
];

High-Security Website

return [
	'htaccess_config' => [
		'domain' => 'secure-site.com',
		'force_https' => true,
		'security_headers' => true,
		'additional_security_headers' => true,
		'request_rate_limiting' => true,
		'max_requests_per_second' => 5,
		'ip_blacklist' => ['192.168.1.100'],
		'country_blacklist' => ['CN', 'RU'],
		'ssl_requirements' => [
			'min_version' => 'TLSv1.3',
			'enforce_hsts' => true,
			'hsts_max_age' => 63072000 // 2 years
		]
	]
];

WordPress Website

return [
	'htaccess_config' => [
		'domain' => 'myblog.com',
		'force_https' => true,
		'protect_wp_admin' => true,
		'protect_sensitive_files' => true,
		'block_php_upload_exec' => true,
		'www_redirection' => 'non-www',
		'error_pages' => ['404' => '/404.php']
	]
];

E-commerce Website

return [
	'htaccess_config' => [
		'domain' => 'mystore.com',
		'force_https' => true,
		'security_headers' => true,
		'cors_headers' => true,
		'cors_domains' => ['api.mystore.com', 'checkout.mystore.com'],
		'ssl_requirements' => [
			'min_version' => 'TLSv1.2',
			'enforce_hsts' => true
		],
		'redirect_management_enabled' => true,
		'redirect_list' => [
			'/old-shop /shop 301',
			'/products/old-category /products/new-category 301'
		]
	]
];

๐Ÿ–ฅ๏ธ CLI Tool Features

The command-line tool provides rich output with validation and progress tracking:

๐Ÿš€ Starting .htaccess generation...

๐Ÿ“ Loading configuration from: examples/config.php
โœ… Configuration loaded successfully!
๐Ÿ” Validating configuration...
โœ… Configuration is valid!

๐Ÿ“‹ Configuration Summary:
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
Domain              : mywebsite.com
Force HTTPS         : โœ… Yes
Security Headers    : โœ… Enabled
Pretty URLs         : โœ… Enabled (front-controller โ†’ index.php)
Rate Limiting       : โœ… Enabled (15 req/sec)
WWW Redirection     : non-www
CDN Domains         : โœ… 2 domains

โš™๏ธ  Generating .htaccess content...
โœ… .htaccess content generated successfully!
๐Ÿ’พ Writing to file: .htaccess
โœ… File written successfully!

๐ŸŽ‰ Generation completed successfully!
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
๐Ÿ“„ Output file: .htaccess
๐Ÿ“Š File size: 4.2 KB
๐Ÿ“ Lines: 156

๐Ÿ“– Preview (first 15 lines):
โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
 1: # Generated by Enhanced .htaccess Generator
 2: # Generated on: 2025-07-11 15:30:45 UTC
 3: # Domain: mywebsite.com
 4:
 5: # Hide server information
 6: ServerSignature Off
 7: ServerTokens Prod
 8:
 9: # ================================
10: # BASIC APACHE OPTIONS
11: # ================================
12: Options -Indexes -MultiViews
13:
14: # Force UTF-8 encoding
15: AddDefaultCharset utf-8
... (and 141 more lines)

โœจ .htaccess file is ready for deployment!

CLI Command Options

# Help
vendor/bin/generate-htaccess --help

# Version
vendor/bin/generate-htaccess --version

# Debug mode
vendor/bin/generate-htaccess config.php --debug

# Different environments
vendor/bin/generate-htaccess config/development.php dev/.htaccess
vendor/bin/generate-htaccess config/production.php .htaccess

๐Ÿ”ง Configuration Reference

Core Options

Option Type Default Description
domain string '' Main website domain
force_https boolean true Redirect HTTP to HTTPS
security_headers boolean true Add security headers
compression boolean true Enable Gzip compression
enable_caching boolean false Set browser cache headers

Pretty URLs Options

Option Type Values Description
pretty_urls boolean false Enable URL rewriting
mode string 'front-controller', 'extension-removal', 'both' Routing mode
handler_file string 'index.php' Front controller file
url_parameter_name string 'url' Query parameter name
force_trailing_slash boolean false Add/remove trailing slashes

Security Options

Option Type Default Description
content_security_policy boolean true Enable CSP headers
block_bad_bots boolean true Block malicious crawlers
protect_sensitive_files boolean true Protect config files
request_rate_limiting boolean true Limit requests per IP
max_requests_per_second integer 10 Rate limit threshold

Performance Options

Option Type Values Description
cache_html_duration string '1 month' HTML cache duration
cache_images_duration string '1 year' Image cache duration
use_webp boolean true WebP image support
enable_gzip_compression boolean false Alternative Gzip setting

๐Ÿ“‚ Project Structure

yobuild/htaccess-generator/
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ HtaccessGenerator.php    # Main generator class
โ”œโ”€โ”€ bin/
โ”‚   โ””โ”€โ”€ generate-htaccess        # CLI executable
โ”œโ”€โ”€ examples/
โ”‚   โ”œโ”€โ”€ config.php               # Full configuration example
โ”‚   โ”œโ”€โ”€ simple-config.php        # Basic configuration
โ”‚   โ”œโ”€โ”€ example-config.php       # Detailed example
โ”‚   โ”œโ”€โ”€ pretty-urls-example.php  # Pretty URLs examples
โ”‚   โ””โ”€โ”€ my-config.php            # Custom configuration
โ”œโ”€โ”€ index.html                   # Web interface
โ”œโ”€โ”€ ajax.php                     # Web interface backend
โ”œโ”€โ”€ composer.json                # Composer configuration
โ”œโ”€โ”€ .editorconfig               # Code style configuration
โ”œโ”€โ”€ .gitignore                  # Git ignore rules
โ”œโ”€โ”€ LICENSE                     # MIT license
โ””โ”€โ”€ README.md                   # This file

๐Ÿ› ๏ธ Integration Examples

Router Implementation (index.php)

<?php
// Get the requested URL from pretty URLs
$requestPath = $_GET['url'] ?? '';
$requestPath = trim($requestPath, '/');

// Define routes
$routes = [
	'' => 'pages/home.php',
	'about' => 'pages/about.php',
	'contact' => 'pages/contact.php',
	'blog' => 'pages/blog.php',
	'blog/(.+)' => 'pages/blog-post.php'
];

// Route matching
foreach ($routes as $pattern => $file) {
	if ($pattern === $requestPath) {
		include $file;
		exit;
	}

	// Regex patterns
	if (preg_match("#^{$pattern}$#", $requestPath, $matches)) {
		$_ROUTE_PARAMS = array_slice($matches, 1);
		include $file;
		exit;
	}
}

// 404 fallback
http_response_code(404);
include 'pages/404.php';

Environment-Specific Deployment

#!/bin/bash
# deploy.sh
ENVIRONMENT=${1:-production}

echo "Deploying for $ENVIRONMENT environment..."
vendor/bin/generate-htaccess "config/${ENVIRONMENT}.php" ".htaccess"
echo "โœ… .htaccess generated for $ENVIRONMENT"

# Upload to server
if [ "$ENVIRONMENT" = "production" ]; then
	rsync -av .htaccess user@server:/var/www/html/
fi

๐Ÿ” Validation and Error Handling

The generator includes comprehensive validation:

  • Domain Format: Validates domain name syntax
  • IP Addresses: Validates IPv4/IPv6 and CIDR notation
  • Country Codes: Ensures 2-letter ISO country codes
  • File Paths: Validates error page and handler file paths
  • Configuration Syntax: Checks array structure and types

Example validation output:

โŒ Configuration validation failed:
   โ€ข Invalid IP address in blacklist: 999.999.999.999
   โ€ข Invalid country code: USA (must be 2-letter ISO code)
   โ€ข pretty_urls_config.handler_file must be a valid PHP file path

๐Ÿ”ง Advanced Features

Custom MIME Types

'custom_mime_types_enabled' => true,
'custom_mime_types' => [
	'.json application/json',
	'.webp image/webp',
	'.woff2 font/woff2'
]

Hotlink Protection

'hotlink_protection_enabled' => true,
'hotlink_protection_list' => [
	'trusted-partner.com',
	'affiliate-site.com'
]

Custom Error Pages

'error_pages' => [
	'404' => '/errors/404.html',
	'500' => '/errors/500.html',
	'403' => '/errors/forbidden.html'
]

Custom .htaccess Rules

'custom_rules' => [
	'# Custom API rate limiting',
	'<LocationMatch "^/api/">',
	'    SetEnvIf Request_URI "^/api/" api_request',
	'</LocationMatch>'
]

๐Ÿš€ Best Practices

  1. Security First: Always enable basic security features
  2. Test Locally: Test generated .htaccess files in development
  3. Backup: Keep backups of working .htaccess files
  4. Environment Separation: Use different configs for dev/staging/production
  5. Version Control: Track configuration changes in git
  6. Documentation: Comment your configuration choices

๐Ÿงช Testing

Test your generated .htaccess file:

# Check Apache syntax
apache2ctl configtest

# Test specific URLs
curl -I https://yourdomain.com/test-url

# Check security headers
curl -I https://yourdomain.com/

๐Ÿ“‹ Requirements

  • PHP: 8.2 or higher
  • Apache Modules: mod_rewrite, mod_headers, mod_deflate, mod_expires
  • Composer: For package installation (optional)

๐Ÿค Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Follow the coding standards (tabs, PHP 8.2+, OOP)
  4. Add tests for new features
  5. Submit a pull request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ†˜ Support

๐Ÿ”— Related Resources

Made with โค๏ธ by Yohn | YoBuild