Skip to content

Instantly share code, notes, and snippets.

@elico
Created November 4, 2023 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elico/53c8b48f8f96bc1851c6346cc931e6ce to your computer and use it in GitHub Desktop.
Save elico/53c8b48f8f96bc1851c6346cc931e6ce to your computer and use it in GitHub Desktop.
Wordpress htaccess generator
<?php
// Define the opening and closing comments to identify the section in .htaccess
$openingComment = "# BEGIN Custom .htaccess Configuration";
$closingComment = "# END Custom .htaccess Configuration";
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$scriptName = pathinfo($_SERVER['SCRIPT_NAME'], PATHINFO_BASENAME);
$requestPath = str_replace('/' . $scriptName, '', $requestPath);
// Decode the percent-encoded characters in the request path
$requestPath = urldecode($requestPath);
// Define the new content to replace the section between the comments
$newContent = "
# BEGIN Custom .htaccess Configuration
# Enable Rewrite Engine
RewriteEngine On
# Set HTTP_AUTHORIZATION environment variable
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# RewriteBase for the dynamic path
RewriteBase $requestPath
# Rewrite rule for clean URLs
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . $requestPath/index.php [L]
# END Custom .htaccess Configuration
";
// Get the path to the .htaccess file in the current directory
$htaccessFilePath = __DIR__ . '/.htaccess.in';
// Check if the .htaccess file exists
if (file_exists($htaccessFilePath)) {
// Read the existing .htaccess content
$currentContent = file_get_contents($htaccessFilePath);
// Find the position of the opening and closing comments
$openingPos = strpos($currentContent, $openingComment);
$closingPos = strpos($currentContent, $closingComment);
// Replace the section between the comments with the new content
if ($openingPos !== false && $closingPos !== false) {
$currentContent = substr_replace($currentContent, $newContent, $openingPos, $closingPos - $openingPos + strlen($closingComment));
} else {
echo "Failed to find the specified comments in the .htaccess file.";
}
} else {
// If the file doesn't exist, create it with the new content
$currentContent = $newContent;
}
// Write the updated or new content to the .htaccess file
if (file_put_contents($htaccessFilePath, $currentContent)) {
echo "The .htaccess.in file has been updated or created in the current directory.";
} else {
echo "Failed to update or create the .htaccess.in file.";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment