yobuild / htaccess-generator
Enhanced .htaccess generator with comprehensive security, performance, and pretty URLs configuration
dev-main
2025-07-15 10:31 UTC
Requires
- php: >=8.2
This package is auto-updated.
Last update: 2025-07-15 10:31:49 UTC
README
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
- Open
index.html
in your web browser - Configure options using the Bootstrap form interface
- Click "Generate .htaccess" to create your configuration
- 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
- Security First: Always enable basic security features
- Test Locally: Test generated
.htaccess
files in development - Backup: Keep backups of working
.htaccess
files - Environment Separation: Use different configs for dev/staging/production
- Version Control: Track configuration changes in git
- 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:
- Fork the repository
- Create a feature branch
- Follow the coding standards (tabs, PHP 8.2+, OOP)
- Add tests for new features
- Submit a pull request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Support
- Documentation: Check this README and example configurations
- Issues: GitHub Issues
- Apache Docs: Apache HTTP Server Documentation