How to Secure Wordpress Website
How to Secure WordPress Website WordPress powers over 43% of all websites on the internet, making it the most popular content management system (CMS) in the world. Its open-source nature, extensive plugin ecosystem, and user-friendly interface have made it the go-to choice for bloggers, businesses, and developers alike. However, this widespread adoption also makes WordPress a prime target for cybe
How to Secure WordPress Website
WordPress powers over 43% of all websites on the internet, making it the most popular content management system (CMS) in the world. Its open-source nature, extensive plugin ecosystem, and user-friendly interface have made it the go-to choice for bloggers, businesses, and developers alike. However, this widespread adoption also makes WordPress a prime target for cybercriminals. According to recent reports, nearly 80% of all website attacks target WordPress sites. The consequences of a compromised site can be devastating—ranging from data theft and SEO sabotage to complete site defacement or blacklisting by search engines.
Securing your WordPress website is not an optional task—it’s a fundamental requirement for maintaining trust, protecting user data, preserving search engine rankings, and ensuring business continuity. A single vulnerability in a plugin, theme, or configuration can open the door to malware injections, brute force attacks, SQL injections, and even the use of your server to launch attacks on other sites. The good news? With the right knowledge and proactive measures, you can dramatically reduce your risk and build a WordPress site that is resilient, secure, and trustworthy.
This comprehensive guide walks you through every critical step to secure your WordPress website—from foundational hardening techniques to advanced monitoring strategies. Whether you’re a beginner managing a personal blog or an experienced developer overseeing a high-traffic e-commerce store, this tutorial provides actionable, real-world solutions designed to keep your site safe from the most common and dangerous threats.
Step-by-Step Guide
1. Keep WordPress Core, Themes, and Plugins Updated
The most common entry point for attackers is outdated software. WordPress frequently releases security patches to fix vulnerabilities discovered in its core code, themes, and plugins. Failing to update leaves your site exposed to known exploits that hackers automate and target at scale.
Always enable automatic updates for WordPress core. Navigate to your WordPress dashboard, go to Settings > General, and ensure your site is running the latest version. For enhanced control, add the following line to your wp-config.php file:
define( 'WP_AUTO_UPDATE_CORE', true );
This enables automatic updates for minor releases. For major updates, test them first on a staging environment to avoid breaking functionality.
Regularly review your installed themes and plugins. Delete any that are unused, abandoned, or no longer maintained. Outdated plugins like Revolution Slider, WPForms (older versions), and WooCommerce extensions have been exploited in the past. Use the WordPress Dashboard > Plugins and Appearance > Themes sections to check for updates. Enable notifications for updates and apply them immediately after testing.
2. Use Strong, Unique Passwords and Enable Two-Factor Authentication (2FA)
Weak passwords remain one of the leading causes of WordPress breaches. Attackers use automated tools to guess common passwords like “password123” or “admin.” Even if your username isn’t “admin,” predictable combinations are still vulnerable.
Require all users—especially administrators—to use strong passwords. A strong password should be at least 12 characters long and include a mix of uppercase and lowercase letters, numbers, and symbols. Avoid dictionary words or personal information like birthdays.
Implement two-factor authentication (2FA) to add an extra layer of security. Even if a password is compromised, 2FA prevents unauthorized access by requiring a time-based one-time code from an authenticator app like Google Authenticator, Authy, or Microsoft Authenticator.
Install a trusted 2FA plugin such as Wordfence or Two Factor Authentication by WPForms. Configure it to require 2FA for all administrative users. You can also enforce 2FA for specific user roles. Test the setup by logging out and logging back in to ensure the second step works correctly.
3. Change the Default Admin Username
The default username “admin” is a well-known target for brute force attacks. Hackers use scripts that automatically try thousands of password combinations against the username “admin.”
To mitigate this, create a new administrator account with a unique, non-guessable username (e.g., “site_manager_01”). Log in with the new account, then delete the original “admin” account. If you cannot delete it (e.g., if it’s tied to content), change its role to “Subscriber” to remove administrative privileges.
To create a new user:
- Go to Users > Add New
- Enter a strong username and password
- Set the role to “Administrator”
- Click “Add User”
After verifying the new account works, return to the original “admin” account and change its role to “Subscriber.” Then delete the account if possible.
4. Limit Login Attempts
Brute force attacks involve automated bots repeatedly trying to guess login credentials. Without protection, these attacks can overload your server and eventually succeed.
Install a plugin like Wordfence or Login LockDown to limit login attempts. Configure it to lock out an IP address after 3–5 failed attempts for 15–30 minutes. This significantly slows down attackers and reduces the likelihood of success.
Wordfence also provides a firewall that blocks known malicious IPs before they even reach your login page. Enable its “Live Traffic” and “Brute Force Protection” features. Monitor the firewall logs regularly to identify patterns of suspicious activity.
5. Secure wp-config.php
The wp-config.php file contains your database credentials, security keys, and other critical configuration settings. If an attacker gains access to this file, they can extract your database password and potentially take over your entire site.
Ensure this file is not accessible via the web. Add the following code to your site’s root .htaccess file (Apache servers):
<Files wp-config.php>
order allow,deny
deny from all
</Files>
For Nginx servers, add this to your server block configuration:
location = /wp-config.php {
deny all;
return 404;
}
Also, verify that your wp-config.php uses unique security keys. These keys encrypt data stored in user cookies. If they are default or missing, attackers can hijack authenticated sessions.
Generate new, cryptographically secure keys by visiting https://api.wordpress.org/secret-key/1.1/salt/. Replace the existing keys in your wp-config.php file with the new ones. Save the file and clear your browser cache.
6. Change the WordPress Database Prefix
By default, WordPress uses “wp_” as the prefix for all database tables (e.g., wp_posts, wp_users). This makes it easier for attackers to guess table names during SQL injection attempts.
During a fresh WordPress installation, you can change the database prefix by editing the $table_prefix variable in wp-config.php:
$table_prefix = 'myblog_';
If you’re securing an existing site, changing the prefix requires more steps:
- Backup your database.
- Use phpMyAdmin or a similar tool to rename all tables from “wp_” to your new prefix (e.g., “myblog_”).
- Update the “wp_usermeta” table to rename keys like “wp_capabilities” to “myblog_capabilities”.
- Update any plugins or custom code that references hardcoded table names.
While this doesn’t prevent SQL injection on its own, it adds a layer of obscurity that deters automated attacks.
7. Disable File Editing in the WordPress Dashboard
By default, WordPress allows administrators to edit theme and plugin files directly from the dashboard. This is convenient for developers but dangerous if an attacker gains admin access—they can inject malicious code into core files without needing FTP or SSH access.
Prevent this by adding the following line to your wp-config.php file, just above the line that says “That’s all, stop editing!”:
define( 'DISALLOW_FILE_EDIT', true );
This disables the Theme Editor and Plugin Editor under Appearance > Theme Editor and Plugins > Plugin Editor. You’ll still be able to edit files via FTP or your hosting control panel, but the risk of remote code injection through the dashboard is eliminated.
8. Secure the .htaccess File
The .htaccess file controls server behavior for Apache-based hosting. You can harden your site by restricting access to sensitive files and blocking common attack vectors.
Add the following code to your root .htaccess file (backup first):
Block suspicious query strings
RewriteEngine On
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [NC,OR]
RewriteCond %{QUERY_STRING} (\|/|..|\.|\.\/|\.\\|\.\\) [NC]
RewriteRule .* - [F]
Block access to wp-config.php
<Files wp-config.php>
Order Allow,Deny
Deny from all
</Files>
Block access to hidden files
<FilesMatch "^\.">
Order Allow,Deny
Deny from all
</FilesMatch>
Disable directory browsing
Options -Indexes
Protect the .htaccess file itself
<Files .htaccess>
Order Allow,Deny
Deny from all
</Files>
This code blocks common injection attempts, prevents access to hidden files (like .env or .git), disables directory listing, and protects the .htaccess file from being read or modified remotely.
9. Install an SSL Certificate
SSL (Secure Sockets Layer) encrypts data transmitted between a visitor’s browser and your server. Without HTTPS, login credentials, form submissions, and cookies can be intercepted on public networks.
Most hosting providers now offer free SSL certificates through Let’s Encrypt. Log in to your hosting control panel (cPanel, Plesk, etc.) and enable SSL for your domain. Once installed, force all traffic to use HTTPS by adding this code to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
After enabling HTTPS, update your WordPress site URL. Go to Settings > General and change both “WordPress Address (URL)” and “Site Address (URL)” to use https:// instead of http://.
Use tools like SSL Labs to test your SSL configuration and ensure there are no vulnerabilities like expired certificates or weak cipher suites.
10. Disable XML-RPC (If Not Needed)
XML-RPC is a legacy API that allows remote publishing and communication between WordPress sites and apps like mobile editors. However, it’s frequently abused in brute force attacks and DDoS amplification attacks.
If you don’t use WordPress mobile apps, Jetpack, or other services that rely on XML-RPC, disable it entirely. Add this code to your .htaccess file:
<Files xmlrpc.php>
Order Deny,Allow
Deny from all
</Files>
Alternatively, use a plugin like Disable XML-RPC to block access without editing server files.
If you need XML-RPC for legitimate services (e.g., Jetpack), restrict access to specific IPs using server-level firewall rules.
11. Secure Your wp-admin and wp-login.php Pages
The login page is the most frequently targeted entry point. Protect it by restricting access to trusted IPs only.
Add this code to your .htaccess file to allow access only from your office or home IP address:
<Files wp-login.php>
Order Deny,Allow
Deny from all
Allow from 192.168.1.100
Allow from 203.0.113.45
</Files>
Replace the IP addresses with your own. You can find your public IP by searching “what is my ip” in Google.
If you have dynamic IPs or need remote access, use a VPN with a static IP or implement IP whitelisting through your hosting provider’s firewall.
12. Use a Web Application Firewall (WAF)
A Web Application Firewall acts as a shield between your website and the internet. It filters malicious traffic before it reaches your server, blocking SQL injection, cross-site scripting (XSS), and other common attacks.
Two popular options are:
- Wordfence – Free and powerful with a built-in firewall, malware scanner, and login security.
- Cloudflare – Offers a free WAF, CDN, DDoS protection, and SSL. Configure Cloudflare’s “Security Level” to “Medium” or “High” and enable “Under Attack Mode” during active attacks.
Install Wordfence from the WordPress plugin repository. After activation, run a full scan and enable the firewall. Review the firewall logs weekly to understand attack patterns.
With Cloudflare, point your domain’s DNS to Cloudflare’s nameservers. Enable the WAF and create custom rules to block common exploit patterns (e.g., requests containing “eval(” or “base64_decode”).
13. Disable Directory Indexing
Directory indexing allows visitors to view a list of files in a folder if no index file (like index.php) is present. This can expose sensitive files like backups, configuration files, or plugin directories.
Add this line to your .htaccess file:
Options -Indexes
This prevents directory listing across your entire site. Test it by visiting a directory URL like yourdomain.com/wp-content/uploads/. You should see a “403 Forbidden” error, not a file list.
14. Regularly Backup Your Website
No security measure is 100% foolproof. If your site is compromised, a clean backup is your lifeline.
Use a reliable backup plugin like UpdraftPlus, BlogVault, or Jetpack Backup. Configure automated daily backups stored offsite (e.g., Google Drive, Dropbox, Amazon S3).
Test your restore process at least once every three months. A backup is useless if you can’t restore from it. Store at least three generations of backups: daily, weekly, and monthly.
Never store backups on the same server as your live site. If the server is compromised, attackers can delete or corrupt your backups.
15. Monitor for Malware and Suspicious Activity
Malware can hide in theme files, plugin code, or database entries. Regular scanning is essential.
Use Wordfence or Sucuri SiteCheck to scan your site weekly. These tools detect hidden iframes, malicious redirects, base64-encoded scripts, and known malware signatures.
Set up email alerts for file changes. Wordfence can notify you when core files, plugins, or themes are modified. This helps you catch unauthorized changes immediately.
Check your site’s Google Search Console for security alerts. If Google flags your site as “compromised,” it will display warnings to users and hurt your rankings.
Monitor your site’s traffic using Google Analytics or Matomo. Look for unusual spikes in traffic from unknown sources, especially from regions you don’t serve. This could indicate a spam injection or botnet activity.
Best Practices
Use a Secure Hosting Provider
Your hosting environment plays a critical role in WordPress security. Shared hosting is cost-effective but often lacks robust security controls. Consider upgrading to managed WordPress hosting (e.g., Kinsta, WP Engine, SiteGround) or a VPS with hardened configurations.
Look for hosts that offer:
- Automatic WordPress updates
- Daily backups with one-click restore
- Server-level firewalls
- DDoS protection
- Malware scanning and removal
- PHP version management
Managed hosts often include built-in security features that reduce your administrative burden and provide faster response times during attacks.
Minimize Plugin Usage
Every plugin you install is a potential vulnerability. Only use plugins from reputable developers with regular updates and large user bases. Avoid “nulled” or pirated plugins—they often contain backdoors.
Before installing a plugin:
- Check its last update date (should be within the last 3–6 months)
- Review the number of active installations (10,000+ is ideal)
- Read recent reviews for security complaints
- Check if the developer has a security policy page
Replace plugins with native WordPress functionality when possible. For example, use WordPress’s built-in comment system instead of third-party comment plugins.
Use a Non-Standard Port for SSH (If Applicable)
If you have SSH access to your server, change the default SSH port from 22 to a random high port (e.g., 2222 or 5555). This reduces exposure to automated bot scans that target port 22.
Edit your SSH configuration file (/etc/ssh/sshd_config):
Port 2222
Restart the SSH service and update your connection settings. Don’t forget to update your firewall rules to allow the new port.
Disable PHP Execution in Uploads Directory
Attackers often upload malicious PHP files disguised as images to the /wp-content/uploads/ directory. Once uploaded, they execute them to gain control.
Add a .htaccess file inside /wp-content/uploads/ with this content:
<Files *.php>
Deny from all
</Files>
This prevents any PHP file uploaded to the media library from being executed. You can still view and serve images, PDFs, and other files normally.
Keep PHP Updated
WordPress runs on PHP. Older PHP versions (e.g., 5.6, 7.0, 7.1) have known security vulnerabilities and are no longer supported.
Use PHP 8.0 or higher. Most modern hosts allow you to change PHP versions via cPanel or a dashboard setting. Test your site after upgrading—some legacy plugins may break. Use the Health Check & Troubleshooting plugin to test in safe mode before switching.
Remove Unused Themes and Plugins
Even inactive themes and plugins can be exploited. Attackers scan for known vulnerabilities in any installed code, regardless of activation status.
Go to Appearance > Themes and delete all themes except your active one. Go to Plugins and delete any inactive plugins. Clean up your server’s file system to remove leftover directories.
Use a Content Delivery Network (CDN)
A CDN like Cloudflare or StackPath not only improves speed but also enhances security. CDNs absorb DDoS traffic, hide your origin server IP, and filter malicious requests before they reach your host.
Enable Cloudflare’s “Proxy” (orange cloud) for your domain. This masks your server’s real IP address, making it harder for attackers to target your infrastructure directly.
Implement Least Privilege User Roles
Not every user needs administrator access. Assign the minimum required role:
- Authors – Can write and publish their own posts
- Editors – Can manage all posts and pages
- Contributors – Can write posts but not publish
- Subscribers – Can only manage their profile
Use a plugin like User Role Editor to customize roles if needed. Avoid giving clients or team members admin access unless absolutely necessary.
Regularly Audit User Accounts
Former employees, freelancers, or collaborators may retain access long after their work is done. Review your user list monthly.
Go to Users > All Users and delete inactive accounts. Change passwords for all remaining accounts. Enable 2FA for all users with editing privileges.
Monitor File Permissions
Incorrect file permissions can allow attackers to write or execute files. Set the following permissions:
- Files: 644
- Folders: 755
- wp-config.php: 600 or 640
You can set permissions via FTP or SSH:
find /path/to/wordpress -type f -exec chmod 644 {} \;
find /path/to/wordpress -type d -exec chmod 755 {} \;
chmod 600 /path/to/wordpress/wp-config.php
Never set files to 777—it grants full read, write, and execute permissions to everyone and is a major security risk.
Tools and Resources
Security Plugins
- Wordfence – Comprehensive security suite with firewall, malware scanner, login security, and real-time threat defense.
- Sucuri Security – Offers malware scanning, firewall, and site hardening tools with excellent support.
- iThemes Security Pro – Includes brute force protection, file change detection, and two-factor authentication.
- MalCare – Automated malware removal and real-time monitoring with a clean interface.
- Two Factor Authentication – Simple, reliable 2FA plugin compatible with Google Authenticator.
Online Scanners
- Sucuri SiteCheck – Free online scanner that checks for malware, blacklisting, and vulnerabilities.
- Quttera Web Malware Scanner – Detects malware, phishing, and suspicious code.
- Google Safe Browsing – Check if your site is flagged by Google for malware or phishing.
- SSL Labs SSL Test – Evaluates your SSL/TLS configuration for weaknesses.
Security Checklists
- WordPress Hardening Guide – Official documentation from WordPress.org
- CIS WordPress Benchmark – Industry-standard security configuration guide
- OWASP Top 10 for WordPress – Lists the most critical web application risks specific to WordPress
Backup Tools
- UpdraftPlus – Most popular backup plugin with cloud storage integration
- BlogVault – Real-time backups and one-click staging
- Jetpack Backup – Integrated with Jetpack suite, includes malware scanning
Monitoring and Alerts
- UptimeRobot – Monitors site uptime and sends alerts via email or SMS
- Google Search Console – Alerts for security issues and indexing problems
- Cloudflare Analytics – Tracks traffic patterns and attack attempts
Real Examples
Case Study 1: Brute Force Attack on a Small Business Site
A local bakery’s WordPress site was compromised after using the username “admin” and a weak password. Attackers used a botnet to guess passwords for over 72 hours until they gained access. Once inside, they injected malicious JavaScript into the homepage that redirected visitors to a phishing site.
After discovering the breach, the owner restored from a clean backup, installed Wordfence, changed all passwords, enabled 2FA, and restricted wp-login.php to their office IP. Within 48 hours, Google removed the warning, and traffic returned to normal. The site has remained secure for over 18 months since.
Case Study 2: Compromised Plugin Leading to Data Theft
An e-commerce site used a popular but abandoned WooCommerce extension that contained a backdoor. The plugin allowed attackers to access customer data, including email addresses and partial credit card numbers.
The breach was detected when customers reported phishing emails. The site owner used Sucuri to scan the site, identified the malicious plugin, removed it, and updated all plugins. They also reset all customer passwords and notified affected users. The incident led to improved security policies, including mandatory plugin reviews and bi-weekly audits.
Case Study 3: Server-Level Compromise via Outdated PHP
A developer’s portfolio site ran on PHP 5.6. An exploit in an outdated PHP module allowed attackers to gain shell access to the server. They installed a cryptocurrency miner that consumed 90% of CPU resources, slowing down the site and increasing hosting costs.
The host flagged the activity due to resource abuse. The developer upgraded to PHP 8.1, removed all compromised files, changed server passwords, and implemented a WAF. They now use managed WordPress hosting with automatic updates and daily malware scans.
Case Study 4: SEO Spam Injection via Insecure Theme
A news site used a free theme downloaded from an untrusted source. The theme contained hidden code that injected spam links into every page, targeting keywords like “viagra” and “casino.” Google penalized the site, dropping it from the first page to page 50+.
After manual cleanup and a reconsideration request, the site was reinstated. The owner switched to a premium theme from ThemeForest, disabled file editing, and installed Wordfence. They now only use themes with verified developer support and regular updates.
FAQs
How often should I update WordPress?
Update WordPress core, themes, and plugins as soon as updates are available. Enable automatic updates for minor releases. Test major updates on a staging site first.
Is WordPress inherently insecure?
No. WordPress itself is secure when properly maintained. The majority of breaches result from outdated software, weak passwords, or poorly coded plugins—not flaws in the core system.
Can I secure my WordPress site for free?
Yes. Many essential security measures—like strong passwords, 2FA, .htaccess hardening, SSL, and free plugins like Wordfence—are completely free. Paid tools offer automation and advanced features but are not mandatory for basic security.
What should I do if my site is hacked?
1. Take the site offline temporarily.
2. Restore from a clean backup.
3. Change all passwords (WordPress, hosting, FTP, database).
4. Update everything (core, plugins, themes).
5. Scan for malware using Sucuri or Wordfence.
6. Review user accounts and remove suspicious ones.
7. Monitor for recurring issues.
Do I need a security plugin?
Yes. While manual hardening helps, security plugins automate critical tasks like firewall protection, malware scanning, login security, and file monitoring. They are essential for ongoing protection.
How do I know if my site is blacklisted?
Check Google Search Console for security alerts. Use Sucuri SiteCheck or Google Safe Browsing to scan your site. If users see warnings like “This site may be hacked,” your site is flagged.
Can hackers steal my WordPress database?
Yes, through SQL injection or direct database access if credentials are exposed. Always use strong passwords, change the database prefix, and restrict database user permissions to only what’s necessary.
Should I disable comments?
If you don’t need user comments, disable them entirely under Settings > Discussion. If you do, use Akismet or Wordfence to filter spam automatically.
What’s the biggest mistake people make?
Ignoring updates. Most breaches occur because site owners delay or skip updates, assuming “it’s not important” or “it might break something.” Proactive maintenance prevents 90% of attacks.
How do I test if my site is secure?
Run a scan with Sucuri SiteCheck or Wordfence. Check your SSL certificate with SSL Labs. Review your .htaccess and file permissions. Ensure 2FA is enabled. Confirm all plugins are updated and from trusted sources.
Conclusion
Securing a WordPress website is not a one-time task—it’s an ongoing discipline. The threats evolve daily, and attackers are increasingly sophisticated. But with the right mindset and consistent practices, you can build a site that is not only functional and fast but also resilient against the most common and damaging attacks.
This guide has provided you with a comprehensive, step-by-step roadmap—from foundational hardening like updating software and changing passwords, to advanced techniques like firewall configuration, file permission management, and malware monitoring. Each step builds upon the last, creating layers of defense that make your site significantly harder to compromise.
Remember: security is not about perfection—it’s about reducing risk. Even implementing half of these measures dramatically lowers your exposure. Prioritize the most critical actions first: update everything, enable 2FA, install a firewall, and back up regularly.
As you implement these strategies, document your changes, schedule monthly audits, and stay informed about emerging threats. The goal isn’t to fear attacks—it’s to outsmart them. A secure WordPress site protects your reputation, your users, and your business. Invest the time now, and you’ll save yourself from costly, stressful breaches later.
Stay vigilant. Stay updated. Stay secure.