MediaWiki Security Hardening Guide
A MediaWiki installation that was set up correctly and then left alone will gradually become a security liability. PHP versions reach end-of-life, MediaWiki itself publishes security releases, and extensions accumulate known vulnerabilities that only get patched if someone is watching for them. Security hardening is not a one-time task — it is an ongoing discipline with a clear set of practical steps.
This guide covers the specific settings, configurations, and operational habits that keep a MediaWiki installation secure, based on MediaWiki's official security documentation and established server-hardening practice. It assumes a working installation already exists. For setting one up from scratch, see "How to Install MediaWiki on Ubuntu Server".
Why MediaWiki Security Matters
A wiki that stores internal documentation, policies, or institutional knowledge is a meaningful target. Unauthorised access can expose confidential information, allow content to be altered without detection, or allow a compromised server to attack other systems. MediaWiki installations that have not been updated in several years — a surprisingly common situation — are often running against known, publicly documented vulnerabilities that automated scanners actively look for.
MediaWiki's own security manual states its primary recommendation directly: the most important security step is to keep the software up to date.[1] Everything else in this guide builds on that foundation.
Security Hardening at a Glance
| Area | What It Protects Against | Priority |
|---|---|---|
| Software updates | Known vulnerabilities in core, extensions, PHP, and the OS | Critical |
| File permissions | Unauthorised read/write access to configuration and upload files | Critical |
| HTTPS and TLS | Credential interception, session hijacking | Critical |
| LocalSettings.php hardening | Database credential exposure, secret key compromise | Critical |
| Database security | Unauthorised database access, privilege escalation | High |
| Access control and user permissions | Unauthorised editing, anonymous abuse | High |
| Password policy | Weak or guessable administrator passwords | High |
| Two-factor authentication via OATHAuth | Account takeover via compromised passwords | High |
| Upload directory security | Malicious file execution via the uploads path | High |
| Anti-spam extensions | Bot account creation, link spam, automated vandalism | Medium |
| PHP configuration | Session token leakage, information disclosure | Medium |
| Monitoring and audit logs | Detecting intrusions and reviewing suspicious activity | Medium |
Step 1: Keep Everything Updated
MediaWiki publishes security releases to its official announcement mailing list, mediawiki-announce. This is a low-traffic list — it only sends new version announcements — and subscribing is the most direct way to receive notification when a security patch is available.[2]
Each standard MediaWiki release receives security support for approximately one year. Older releases may contain known-but-unpatched vulnerabilities, meaning that running a two-year-old release is not just running old software — it may be running software with publicly documented security holes that have not been fixed because the release is no longer maintained.
Subscribe to the mailing list at:
https://lists.wikimedia.org/postsignup/mediawiki-announce
The update obligation extends beyond MediaWiki core. PHP, Apache or Nginx, MariaDB or MySQL, and the underlying operating system all require regular security patching. MediaWiki's own documentation notes that several installations were compromised in the past not through MediaWiki itself but through other unpatched applications running on the same server.
Check the currently installed version at any time by visiting Special:Version on your wiki.
Step 2: Correct File Permissions
File permissions determine which system users can read, write, or execute each file and directory. Incorrect permissions are one of the most common configuration errors and can allow a compromised PHP process or another user on the same server to read database credentials or write malicious files.
MediaWiki's security manual recommends that the wiki's files should be owned by a user other than the web server account (www-data on Debian and Ubuntu systems). The exception is the images/ directory, which must be writable by the web server to accept uploaded files.[3]
Set ownership of the entire MediaWiki directory to a non-web-server user (replace yourusername with the appropriate system account):
sudo chown -R yourusername:yourusername /var/www/html/w
Re-assign ownership of only the uploads directory back to the web server:
sudo chown -R www-data:www-data /var/www/html/w/images
Remove write access from all non-owner users across the MediaWiki directory:
sudo chmod -R go-w /var/www/html/w
Re-enable write access on the images directory only:
sudo chmod 755 /var/www/html/w/images
LocalSettings.php permissions. This file contains the database password and the secret key. It must be readable by the PHP user but must not be world-readable:
sudo chmod 640 /var/www/html/w/LocalSettings.php
Remove the installation directory after setup. The mw-config/ installer directory serves no purpose on a running wiki and should be removed. Use your server's file manager or SFTP client to delete the mw-config folder from the MediaWiki root directory, or from the command line:
sudo rm -r /var/www/html/w/mw-config
Step 3: Enable and Enforce HTTPS
MediaWiki's security documentation recommends HTTPS to protect against credential interception and session hijacking. Without it, login credentials and session cookies travel across the network in plaintext.
If HTTPS has not been configured yet, see "How to Install MediaWiki on Ubuntu Server" for Certbot setup instructions. Once HTTPS is in place, configure MediaWiki to use it consistently. In LocalSettings.php, set the server address with the HTTPS protocol:
$wgServer = "https://yourdomain.com";
Force all cookies to be sent over HTTPS only:
$wgCookieSecure = true;
To enable HTTP Strict Transport Security (HSTS) at the web server level, add the following inside the VirtualHost block in the Apache site configuration:
Header always set Strict-Transport-Security "max-age=31536000"
Enable the Apache headers module if not already active:
sudo a2enmod headers
Reload Apache to apply the change:
sudo systemctl reload apache2
Step 4: Harden LocalSettings.php
LocalSettings.php is the central configuration file. It contains the database password, the secret key, and other sensitive settings that require deliberate hardening.
Generate a strong, unique secret key. The installer creates a 64-character random string for $wgSecretKey automatically, but if this was ever shared or exposed it must be replaced. Generate a new value:
openssl rand -hex 32
Then update the value in LocalSettings.php:
$wgSecretKey = "paste_the_generated_value_here";
Set a unique upgrade key:
$wgUpgradeKey = "paste_a_different_unique_value_here";
Move sensitive credentials outside the web root. If a server misconfiguration ever caused PHP to serve files as plaintext, the database password in LocalSettings.php would be exposed. To mitigate this, move credentials into a separate file stored outside the web-accessible directory tree, and load it from LocalSettings.php:
require_once '/etc/mediawiki/db_credentials.php';
Disable debug logging in production. Debug log files contain sensitive data including session information and database queries. MediaWiki's documentation states that debug log files must never be publicly accessible. In LocalSettings.php, confirm the debug log line is commented out:
# $wgDebugLogFile = "/var/log/mediawiki/debug.log";
If it is needed temporarily for troubleshooting, use an absolute path that is outside the web root, and comment it out again immediately when finished.
Step 5: Harden Database Security
MediaWiki's official security documentation recommends keeping database access as restricted as possible.[4]
Restrict the database user's privileges. The MediaWiki database user only needs SELECT, INSERT, UPDATE, and DELETE on the wiki database. It should not hold the FILE privilege or any server-administration privileges.
Log into MariaDB:
sudo mysql -u root -p
Check the current privileges assigned to the wiki user:
SHOW GRANTS FOR 'wikiuser'@'localhost';
If excess privileges exist, remove all existing privileges first:
REVOKE ALL ON *.* FROM 'wikiuser'@'localhost';
Then grant only the four required permissions on the wiki database:
GRANT SELECT ON wikidb.* TO 'wikiuser'@'localhost';
GRANT INSERT ON wikidb.* TO 'wikiuser'@'localhost';
GRANT UPDATE ON wikidb.* TO 'wikiuser'@'localhost';
GRANT DELETE ON wikidb.* TO 'wikiuser'@'localhost';
Apply the changes and exit:
FLUSH PRIVILEGES; EXIT;
Restrict database network access. Unless the database runs on a separate server, it should only accept connections on the local loopback interface. In the MariaDB server configuration file (typically /etc/mysql/mariadb.conf.d/50-server.cnf), confirm the bind-address setting:
bind-address = 127.0.0.1
Restart MariaDB after making this change:
sudo systemctl restart mariadb
This ensures the database cannot be accessed from outside the server even if a firewall rule is accidentally misconfigured.
Step 6: Secure the Upload Directory
File uploads are disabled by default in MediaWiki and must be explicitly enabled. If uploads are enabled, the images/ directory must be writable by the web server — but script execution must be disabled within it. Without this restriction, an attacker who successfully uploads a malicious script could execute it by requesting the file directly.
For Apache, create or edit an .htaccess file inside the images directory:
sudo nano /var/www/html/w/images/.htaccess
Add a single directive to disable PHP processing in that directory:
php_admin_flag engine off
For Nginx, add the following inside the server block to block direct access to any script files uploaded to the images path:
location ~* ^/images/.*\.(php|pl|py|cgi)$ {
return 403;
}
MediaWiki's documentation also notes that for maximum security, uploaded files should be served from a completely separate domain rather than a subdomain, particularly if SVG file uploads are permitted. SVG is closely related to HTML and can contain embedded scripts, making it a higher-risk file type than standard image formats.
Step 7: Configure Access Control and User Permissions
MediaWiki's default configuration allows anonymous users to both read and edit content. For most private or internal wikis this needs to be changed deliberately.
Prevent non-logged-in users from editing pages:
$wgGroupPermissions['*']['edit'] = false;
Prevent open public account registration:
$wgGroupPermissions['*']['createaccount'] = false;
For a fully private wiki where even reading requires a login:
$wgGroupPermissions['*']['read'] = false;
Protect the MediaWiki: namespace. Pages in the MediaWiki: namespace control interface messages and can inject HTML and JavaScript into page output. MediaWiki's security manual notes that anyone who can edit this namespace can introduce arbitrary code into the wiki interface. Verify that only trusted administrators hold the editinterface permission, and that it has not been granted to ordinary users.
Step 8: Enable Two-Factor Authentication (OATHAuth)
The OATHAuth extension provides two-factor authentication for MediaWiki. It supports TOTP authenticator apps (such as Google Authenticator, Authy, and Microsoft Authenticator), hardware security keys, and passkeys. It is bundled with the official MediaWiki tarball.[5]
Enable the extension in LocalSettings.php:
wfLoadExtension( 'OATHAuth' );
To require two-factor authentication for administrator and bureaucrat accounts:
$wgOATHRequiredForGroups = [ 'sysop', 'bureaucrat' ];
Individual users enrol their own 2FA method via Special:Manage_Two-factor_authentication. If a user loses access to their authenticator and their recovery codes, an administrator can disable their 2FA from the command line:
php maintenance/run.php OATHAuth:disableOATHAuthForUser --user=Username
Step 9: Configure a Strong Password Policy
MediaWiki's $wgPasswordPolicy setting controls minimum password requirements for each user group.
A reasonable baseline policy for all users:
$wgPasswordPolicy['policies']['default']['MinimalPasswordLength'] = [ 'value' => 10 ];
$wgPasswordPolicy['policies']['default']['PasswordCannotMatchUsername'] = true;
A stricter minimum length for administrator accounts, with a prompt to change on next login if the password is too short:
$wgPasswordPolicy['policies']['sysop']['MinimalPasswordLength'] = [ 'value' => 14, 'suggestChangeOnLogin' => true ];
$wgPasswordPolicy['policies']['sysop']['PasswordCannotMatchUsername'] = true;
Step 10: Install and Configure Anti-Spam Extensions
For any wiki accessible to the public, spam and bot abuse are real operational problems. The following extensions are all bundled with the official MediaWiki tarball.
| Extension | Purpose |
|---|---|
| ConfirmEdit | CAPTCHA framework triggered on account creation and link additions. QuestyCaptcha (custom question-and-answer) is recommended over the default SimpleCaptcha for production use. |
| AbuseFilter | Allows administrators to define rules that detect and respond to abusive editing patterns — blocking edits, warning users, or preventing account creation based on configurable criteria. |
| SpamBlacklist | Blocks edits that contain URLs matching a configurable blacklist. Can connect to shared community-maintained lists. |
| TitleBlacklist | Prevents creation of pages or accounts with titles matching defined patterns — useful for blocking common spam account naming patterns. |
| CheckUser | Allows administrators to look up the IP addresses behind registered accounts, useful for identifying and blocking coordinated bot campaigns. |
Enable the extensions one at a time in LocalSettings.php. Load ConfirmEdit before AbuseFilter, as MediaWiki's official documentation recommends this order to ensure correct interaction between the two:[6]
wfLoadExtension( 'ConfirmEdit' );
wfLoadExtension( 'AbuseFilter' );
wfLoadExtension( 'SpamBlacklist' );
wfLoadExtension( 'TitleBlacklist' );
wfLoadExtension( 'CheckUser' );
Configure ConfirmEdit to trigger on account creation:
$wgCaptchaTriggers['createaccount'] = true;
Also trigger it when edits add external URLs:
$wgCaptchaTriggers['addurl'] = true;
Step 11: PHP Configuration Security
Several PHP configuration settings affect the security of any PHP-based application. These are set in php.ini or via Apache PHP directives.
| Setting | Recommended Value | Reason |
|---|---|---|
session.use_trans_sid |
Off | Prevents session IDs from appearing in URLs, which can leak via referrer headers |
expose_php |
Off | Prevents PHP version appearing in HTTP response headers |
display_errors |
Off (production) | Prevents PHP error messages from exposing file paths and configuration detail in browser output |
log_errors |
On | Errors should be logged server-side rather than displayed to users |
Verify current values from the command line:
php -i | grep session.use_trans_sid
php -i | grep expose_php
php -i | grep display_errors
Best Practices
Subscribe to the mediawiki-announce mailing list immediately after deployment and treat security announcements as requiring action within days, not weeks. Apply file permission recommendations at initial setup rather than retrofitting them after a problem occurs. Enable HTTPS from the very first day the wiki is accessible. Require two-factor authentication for administrator accounts even if ordinary user accounts are not subject to the same requirement — privileged accounts are higher-value targets. Review the Special:Log pages periodically for unusual patterns in account creation, page deletion, or permission changes. Keep a tested backup and restore process in place so that recovery from a defacement or data loss incident is measured in hours rather than days.
Common Mistakes
The single most common security mistake on MediaWiki installations is not updating the software — installations that were deployed once and never updated, sometimes for years, account for a disproportionate share of real-world compromises. Leaving the installation directory in place after the initial setup leaves a web-accessible entry point that serves no purpose. Leaving LocalSettings.php world-readable exposes the database credentials to any other process on the server. Enabling file uploads without restricting script execution in the uploads directory creates a serious code-execution risk. Treating default $wgGroupPermissions as appropriate for a private wiki without reviewing them is a frequent oversight — by default, MediaWiki allows anonymous reading, which many organisations intend to restrict.
Frequently Asked Questions
How do I know if my MediaWiki installation has security vulnerabilities?
Check the version at Special:Version and compare it against the current release on MediaWiki.org. If the installed version is older than the current release, review the release notes for security fixes. Subscribe to the mediawiki-announce mailing list to receive future notifications automatically.
Is it safe to use MediaWiki without HTTPS?
No, for any wiki where users log in. Without HTTPS, login credentials and session cookies are transmitted in plaintext. MediaWiki's own security documentation specifically recommends HTTPS for all installations.
What should I do if LocalSettings.php has been exposed?
MediaWiki's security manual provides specific guidance: change the database password in $wgDBpassword, replace $wgSecretKey with a newly generated random string, and reset the user_token column in the user table so that any tokens derived from the leaked data cannot be used to impersonate accounts.[7]
Should I disable user account creation entirely on a private wiki?
If the wiki is intended for a known, fixed set of users, disabling public account creation and creating accounts manually for each user is a straightforward and effective approach. Administrators can still create accounts via Special:CreateAccount regardless of the public registration setting.
How do I require two-factor authentication for all administrator accounts?
Add the administrator group name to the $wgOATHRequiredForGroups array after enabling the OATHAuth extension. Users in the required groups who have not yet enrolled a 2FA method will be redirected to enrol before they can complete their next login.
Is it safe to run other applications on the same server as MediaWiki?
Running unrelated web applications on the same server introduces additional attack surface. MediaWiki's own documentation notes historical incidents where wikis were compromised through vulnerabilities in other applications sharing the same server environment.
Conclusion
MediaWiki security hardening is a set of deliberate, documented configuration decisions layered on top of an ongoing commitment to keeping the software current. No single setting provides complete protection — the value comes from combining correct file permissions, HTTPS enforcement, strong access controls, two-factor authentication for privileged accounts, correctly configured anti-spam extensions, and a reliable update process.
Most of the steps in this guide are one-time configurations that, once applied correctly, require only periodic verification rather than repeated effort. The genuinely ongoing obligations are monitoring the security announcement mailing list, applying updates promptly, and keeping the full software stack — not just MediaWiki itself — current.
If an existing installation needs a security review or remediation, or if these settings need to be applied as part of a new deployment, that work is described on SolidWiki's MediaWiki Development Services page.
See Also
- How to Install MediaWiki on Ubuntu Server
- MediaWiki Hosting Guide: Choosing the Right Server for Your Wiki
- MediaWiki SEO Best Practices
- Top 10 MediaWiki Extensions for Business Wikis
- MediaWiki Performance Optimisation
References
- ↑ MediaWiki.org, "Manual: Security", https://www.mediawiki.org/wiki/Manual:Security
- ↑ MediaWiki.org, "Manual: Security", https://www.mediawiki.org/wiki/Manual:Security
- ↑ MediaWiki.org, "Manual: Security", https://www.mediawiki.org/wiki/Manual:Security
- ↑ MediaWiki.org, "Manual: Security", https://www.mediawiki.org/wiki/Manual:Security
- ↑ MediaWiki.org, "Extension: OATHAuth", https://www.mediawiki.org/wiki/Extension:OATHAuth
- ↑ MediaWiki.org, "Extension: ConfirmEdit", https://www.mediawiki.org/wiki/Extension:ConfirmEdit
- ↑ MediaWiki.org, "Manual: Security", https://www.mediawiki.org/wiki/Manual:Security