Solving Magento Media Manager URL Issues
The Problem: Full URLs with _directive Parameters
You’re facing an issue where the built-in Magento File browser is returning URLs that contain _directive parameters when you insert files. These URLs look something like this:
http://www.infira.ee/magento/index.php/admin/cms_wysiwyg/directive/_directive/e3ttZWRpYSB1cmw9Ind5c2l3eWcvc2VhcmNoLnBuZyJ9fQ,,/key/dc3e70661f817703710378d51351495b/
The issue arises when these URLs are used in your CSS files. You want to convert them into clean, absolute paths like this:
http://www.infira.ee/magento/dir/dir/dir/someImage.png
Understanding the Magento _directive
Before we dive into the solution, let’s understand what the _directive parameter is doing. It’s a part of the Magento WYSIWYG (What You See Is What You Get) editor functionality.
The _directive/e3ttZWRpYSB1cmw9Ind5c2l3eWcvc2VhcmNoLnBuZyJ9fQ,,/key/dc3e70661f817703710378d51351495b/ part is actually base64 encoded data. The dc3e70661f817703710378d51351495b at the end is a session key.
Converting Magento Full URLs
Method 1: Customizing the File Browser Behavior
The most straightforward approach is to customize your file browser extension’s behavior. You can modify the script that handles the “Insert File” button click event to parse and decode the base64 data, extract the actual file name and path, and generate a clean URL.
Here’s a simplified example of how you might do this in JavaScript:
function insertFile(url) {
let decoded = atob(url.split('/').pop().split(',')[0]);
let [, filename] = /filename="([^"]+)"/.exec(decoded);
let fileUrl = `http://www.infira.ee/magento/dir/${filename}`;
// Insert the clean URL into your content
}
Method 2: Post-Processing in PHP
If customizing the JavaScript is not an option, you can also process these URLs on the server side using PHP.
function convertUrl($url) {
$parts = explode('/', $url);
$lastPart = end($parts);
list(,$encodedFile) = explode(',', $lastPart);
// Decode the base64 data
$decoded = base64_decode($encodedFile);
preg_match('/filename="([^"]+)"/', $decoded, $matches);
$filename = $matches[1];
return "http://www.infira.ee/magento/dir/{$filename}";
}
Best Practices
- Maintain consistent file path structures to avoid issues with relative paths.
- Consider using version control for your media files and CSS stylesheets. This can help manage changes over time.
Remember, changing URLs in a live Magento store requires careful testing to ensure compatibility across all modules and extensions. Always backup your data before making significant changes.
Conclusion
Converting Magento’s _directive URLs into clean absolute paths involves understanding the base64 encoding used by the WYSIWYG editor and decoding this information. You can either customize the file browser behavior in JavaScript or process the URLs on the server side using PHP.
For more advanced techniques and performance optimizations, consider exploring Laravel Company’s guide to Magento optimization.