Setting Up Your Own Markdown-Based CMS with PHP, HTML, and CSS
Are you tired of the complexities of mainstream CMS platforms? Do you crave a lightweight, customizable solution for your blog? In this guide, we'll walk through the process of setting up your own Markdown-based CMS using PHP, HTML, and CSS. This setup will not only provide SEO-friendly URLs but also allow you to unleash your creativity with custom text formatting structures.
Prerequisites
Before we dive into the setup, ensure you have the following:
- A server with Apache installed
- PHP installed on your server
- Basic knowledge of Apache configuration
- Parsedown library (available on GitHub)
Apache Configuration
First, let's configure Apache to handle SEO-friendly URLs and route requests through index.php
.
<VirtualHost *:443>
ServerName mywebsite.com
DocumentRoot /var/www/blog-directory/
SSLCertificateFile /etc/letsencrypt/live/mywebsite.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/mywebsite.com/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
FallbackResource /index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
</VirtualHost>
Explanation of key configurations:
FallbackResource
: Directs all requests toindex.php
.RewriteCond
: Ensures that existing files are served without redirection.
PHP Code Example
Now, let's create the PHP code that will handle incoming requests and convert Markdown content to HTML.
<?php
// index.php
// Load Parsedown library
require_once 'path/to/parsedown/Parsedown.php';
// Get the URL ending
$requestUri = $_SERVER['REQUEST_URI'];
$slug = ltrim(parse_url($requestUri, PHP_URL_PATH), '/');
// Define the directory for Markdown files
$markdownDirectory = '/path/to/markdown/files/';
// Build the full path to the Markdown file
$markdownFile = $markdownDirectory . $slug . '.md';
// Check if the Markdown file exists
if (file_exists($markdownFile)) {
// Read the Markdown content
$markdownContent = file_get_contents($markdownFile);
// Use Parsedown to convert Markdown to HTML
$parsedown = new Parsedown();
$htmlContent = $parsedown->text($markdownContent);
// Output the HTML content
echo $htmlContent;
} else {
// Handle 404 error or redirect to a default page
header('HTTP/1.0 404 Not Found');
echo '<h1>404 Not Found</h1>';
}
?>
Explanation of key PHP code sections:
$_SERVER['REQUEST_URI']
: Extracts the requested URL.ltrim()
: Removes leading slashes from the URL.file_exists()
: Checks if the Markdown file exists.- Parsedown library: Converts Markdown to HTML.
Conclusion
Congratulations! You've just set up a lightweight, customizable Markdown-based CMS using PHP, HTML, and CSS. This setup not only provides SEO-friendly URLs but also gives you the flexibility to enhance your content with custom text formatting structures. Experiment, iterate, and enjoy the simplicity of your personalized blogging platform.