Web development
How to secure a WordPress website
A multi-layered approach to WordPress security, from .htaccess security headers to firewall plugins, structure obfuscation and operational best practice.

Securing a WordPress website involves a multi-layered approach to protect against cyber threats. Modifying your .htaccess file to include security headers is an essential first step, and combining it with the right plugins and operational habits gives you defence in depth without hurting performance.
The role of the .htaccess file in WordPress security
The .htaccess file is an Apache server configuration file that lets you enforce security measures before WordPress even loads: blocking access to sensitive files, preventing malicious scripts and sending security headers with every response.
Step 1: locate and back up your .htaccess file
Open your hosting file manager or FTP client and find .htaccess in the WordPress root directory. Download a backup copy first, so you can revert immediately if a change causes issues.
Step 2: add security headers
Add the following block to send hardened headers with every response:
# BEGIN Custom security headers
Header unset X-Powered-By
Header unset Server
Header unset X-Pingback
Header set Referrer-Policy "strict-origin-when-cross-origin"
Header set X-Download-Options "noopen"
Header set X-Permitted-Cross-Domain-Policies "none"
Header set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "SAMEORIGIN"
Header always set Content-Security-Policy "upgrade-insecure-requests;"
Header always set Permissions-Policy "accelerometer=(), autoplay=(), camera=(), fullscreen=*, geolocation=(self), gyroscope=(), microphone=(), payment=*"
# END Custom security headers
These headers protect against cross-site scripting, code injection and clickjacking, enforce HTTPS, and tighten how browsers may load your resources. Test with a header checker after saving; overly strict values (particularly Content-Security-Policy) can break third-party embeds, so tighten iteratively.
Step 3: save and verify
Upload the modified file and verify the site loads without errors. If anything breaks, restore the backup and reintroduce headers one at a time.
Leverage advanced security plugins
Wordfence Security
Wordfence provides an all-in-one solution for monitoring and protecting a WordPress site:
- A web application firewall that blocks malicious traffic before it reaches WordPress.
- Brute-force protection that limits failed login attempts.
- A malware scanner that detects threats and backdoors in files and the database.
- Live traffic monitoring for real-time threat identification.
Install it, enable the firewall in learning mode first, turn on login protection, and schedule automated malware scans.
WP Hide and Security Enhancer
WP Hide conceals your WordPress structure, making it harder for attackers to target known vulnerabilities:
- Admin URL customisation: change the default admin path and block the traditional entry points.
- Login page security: replace the standard login URL and add CAPTCHA protection.
- XML-RPC protection: disable the default XML-RPC endpoint or move it to a custom path.
- Theme and plugin path customisation: obfuscate the site structure through URL rewriting.
- Core cleanup: remove version indicators and unnecessary metadata that fingerprint your install.
Other best practices for WordPress security
- Keep WordPress core, themes and plugins updated; most compromises exploit known, patched vulnerabilities.
- Enforce strong, unique passwords for every account.
- Enable two-factor authentication for logins.
- Schedule regular off-site backups so you can recover from any incident.
- Monitor user activity and review accounts periodically.
- Never allow PHP execution inside the uploads directory.
Conclusion
Website security is an ongoing process rather than a single task. Hardening .htaccess with security headers establishes the foundation; a firewall plugin and structure obfuscation add active defence; and disciplined updates, backups and access control keep the whole system resilient, all without sacrificing performance or functionality.
Begin with an inventory and threat model
Security plugins cannot protect a system nobody understands. List the production domain, staging sites, hosting account, DNS provider, CDN, mail service, WordPress administrators, themes, plugins, integrations, scheduled jobs and third-party scripts. Record an owner and business purpose for each. Remove abandoned staging copies and unused administrator accounts before adding another control.
Then consider realistic threats. A public brochure site faces credential stuffing, vulnerable plugins, malicious uploads, search spam and denial of service. A membership or commerce site also holds personal data and exposes authenticated actions. The controls should reflect the data and impact. Obscuring a login URL may reduce automated noise, but it does not replace strong authentication, updates and least privilege.
Use separate credentials for hosting, WordPress, database, SFTP and external services. A password manager should generate and share them. Do not place secrets in theme files, public repositories or screenshots. If the host supports environment variables or a protected configuration outside the web root, use them for API keys. WordPress salts should be unique and can be rotated after a suspected session compromise.
Harden the hosting layer
Use a currently supported PHP release and keep it updated through the hosting panel. Disable directory listing. Ensure files use conservative permissions, commonly files at 0644 and directories at 0755, with tighter values where the host permits. The web process should not be able to modify more than WordPress requires.
Serve the site only over HTTPS and redirect every HTTP request once. Enable HSTS only after every subdomain that will be covered is ready for HTTPS, because browsers remember the policy. Security headers should be tested against the real site. An aggressive Content Security Policy copied from another project can break checkout, forms or the editor; a report-only phase reveals dependencies before enforcement.
Protect configuration and backup files from direct requests. Block execution of PHP in uploads. Deny access to dotfiles, logs and temporary exports. Disable the built-in file editor in the WordPress dashboard so a stolen administrator session cannot modify plugin code as easily. If XML-RPC is not used by an application, disable or restrict it. If it is needed, rate-limit it and monitor authentication attempts.
At the CDN or web application firewall, create rules for abusive login traffic and obvious exploit patterns. Rate limiting should avoid locking legitimate editors behind a shared office address. Keep an emergency allow procedure and document where a block can be reviewed.
Reduce the application attack surface
Every plugin is code running with the site’s privileges. Prefer actively maintained extensions with a clear purpose, reasonable update history and broad scrutiny. Remove deactivated plugins and themes rather than leaving their files accessible. One maintained plugin that performs a necessary function is usually safer than overlapping plugins fighting over caching, login and headers.
Updates need a process. Apply security fixes promptly, but test major changes on a representative staging copy. Staging must be protected with authentication and noindex, use sanitised data where possible and never send real customer email. A backup taken moments before an update is useful only if restoration has been tested.
Custom themes and plugins require code review. Escape output for its HTML context, validate and sanitise input, use nonces for state-changing actions and enforce capability checks on the server. A nonce is not authorisation. Database queries need prepared statements. File uploads need strict type, size and permission checks, and user-supplied filenames should not determine executable paths.
Disable user registration if it serves no purpose. Give editors the editor role, not administrator access. Create a separate administrator account for maintenance rather than using it for daily content work. Review accounts quarterly and immediately after staff or agency changes.
Authentication and session controls
Require multi-factor authentication for every privileged account, including hosting and DNS. Use passkeys or authenticator applications where supported. SMS is better than a password alone but weaker against account takeover and number transfer attacks.
Limit repeated login attempts at the edge and application layer. Alert on a burst of failed attempts, a new administrator, plugin installation, theme editing and changes to critical settings. Avoid exposing usernames through author archive patterns where they are not needed, but do not depend on username secrecy.
Set reasonable session durations and force logout after a password or role change. Administrators should not stay signed in on shared devices. For high-impact sites, restrict administrative access by VPN or identity-aware proxy, while preserving an audited recovery route.
Backups are part of security
Use the 3-2-1 principle as a starting point: multiple copies, on different media or services, with at least one separated from the production account. A backup stored only on the same hosting account can disappear with the compromised site. Encrypt backups containing personal data and restrict who can download them.
Choose frequency from recovery objectives. A brochure site may tolerate a day of lost edits; an order system may not. Back up both files and database on compatible schedules. Record WordPress, PHP and key plugin versions so the environment can be reconstructed.
Test restoration on a non-public location. Verify login, media, forms, scheduled tasks and links after restore. Measure how long it takes. The first time a team discovers that an archive is incomplete should not be during an incident.
Logging, monitoring and file integrity
Monitor uptime, unexpected file changes, administrator activity, failed logins, mail delivery and search indexing. Send alerts somewhere outside the WordPress installation. If the site is compromised, an alert stored only inside it may be altered or lost.
Keep logs long enough to investigate but minimise sensitive content. Do not log passwords, full payment details, authentication cookies or form message bodies unless a documented need and retention policy exist. Protect access logs because IP addresses and request paths can be personal data.
File-integrity monitoring should distinguish planned updates from unexpected modification. Core checksums are useful; custom code needs a known source repository or release package. A changed file is a signal to investigate, not automatic proof of malware.
Secure forms, email and integrations
Every public form needs server-side validation, output escaping, CSRF protection, rate limiting and spam controls. Client validation improves usability but can be bypassed. Use authenticated SMTP rather than relying on unauthenticated server mail, and keep the mail credential out of the public web root where the host allows.
Webhooks should use HTTPS, a secret signature or strong token, narrow permissions and a timeout. Validate the destination and payload. A CRM integration should not receive every field merely because the form collected it. Define retention and deletion across both systems.
Tracking scripts are executable third-party code. Keep a register of each tag, owner and purpose. Load optional analytics only after the appropriate consent. Remove old experiments and agency pixels. Restrict who can publish tag-manager changes, and use approval and version history.
Incident response before the incident
Write a short response runbook with contacts for hosting, DNS, security, legal and communications. Define who can put the site into maintenance, rotate credentials, restore a backup and communicate with affected users. Store the runbook somewhere available when WordPress is not.
If compromise is suspected, preserve evidence before cleaning. Record times, alerts and observed behaviour. Resetting files immediately can destroy clues while leaving the original access route open. Engage a qualified responder for high-impact incidents or regulated data.
Contain access, rotate exposed credentials from a clean device, identify the entry point, rebuild from known-good sources and patch the cause. Do not merely delete visible spam. Review administrators, scheduled tasks, must-use plugins, uploads, database options, injected JavaScript and DNS. Notify regulators or affected people when law and risk assessment require it.
A monthly operating checklist
Review pending updates, administrator accounts, recent backups, restoration test status, firewall events, file changes, certificate expiry, PHP support and third-party tags. Check that security email reaches a monitored mailbox. Search the site for unexpected indexed pages and verify forms still deliver.
Quarterly, remove obsolete plugins, rotate sensitive integration credentials where policy requires, review access with agencies and test the incident runbook. Annually, revisit the threat model and hosting architecture. The site may now collect data or support transactions that were not present when controls were chosen.
Security is strongest when these actions become routine operations. Headers and plugins matter, but ownership, tested recovery and disciplined change management are what keep one vulnerable extension or stolen password from becoming a prolonged business incident.
Apply this to your business
Web development
A fast, accessible website that converts, ranks and can be maintained without a developer on retainer.
Fast, maintainable marketing websites built on modern architecture, migrated cleanly off heavy CMS setups and measured on Core Web Vitals.
- Astro
- React
- TypeScript
- WordPress
Keep reading
web development
Core Web Vitals explained: why performance is your best marketing strategy
What LCP, INP and CLS actually measure, how they influence rankings and conversions, and the practical fixes that move each metric.
Read insightweb development
WordPress vs Drupal: choosing the right CMS for growth
A practical comparison of WordPress and Drupal for teams choosing a CMS that must scale in traffic, content, users and integrations.
Read insight
