Skip to content
  • Quick Ref
  • Contact
  • About
wpcanyon.com

wpcanyon.com

Category: Speed & Security

Serve static 410 for bots hitting wp‑login & xmlrpc

Posted on August 19, 2025 By Admin No Comments on Serve static 410 for bots hitting wp‑login & xmlrpc

Serve static 410 for bots hitting wp-login & xmlrpc

If your WordPress site is frequently targeted by bots attempting to access wp-login.php and xmlrpc.php, it can lead to increased server load and security risks. A quick and effective way to mitigate this is by serving a static HTTP 410 Gone response to these requests. This tells bots that these endpoints are permanently gone, discouraging repeated access attempts.

Quick Fix

  1. Identify your web server type (Apache, Nginx, LiteSpeed, etc.).
  2. Add the appropriate configuration snippet to serve a 410 response for wp-login.php and xmlrpc.php.
  3. Reload or restart your web server to apply changes.
  4. Test by accessing these URLs and confirm you receive a 410 Gone status.

Why this happens

WordPress sites commonly expose wp-login.php and xmlrpc.php files, which are often targeted by bots for brute-force attacks or exploiting XML-RPC vulnerabilities. While legitimate users need wp-login.php to log in, many sites use alternative login methods or restrict access via plugins or IP whitelisting. Similarly, xmlrpc.php is rarely needed and often disabled to prevent abuse.

Serving a 410 Gone status explicitly informs bots that these endpoints are no longer available, reducing unnecessary server load and improving security posture.

Requirements

  • Access to your web server configuration files or control panel (e.g., Apache .htaccess, Nginx config, LiteSpeed config).
  • Basic knowledge of editing server config files or ability to upload files via FTP/SFTP.
  • Ability to reload or restart your web server after changes.
  • Optional: Backup your configuration files before editing.

Step-by-step

1. Determine your web server

Check your hosting environment or server info to confirm if you use Apache, Nginx, LiteSpeed, or another server.

2. Add configuration to serve 410 for wp-login.php and xmlrpc.php

Apache (.htaccess)

# Serve 410 Gone for wp-login.php and xmlrpc.php
<FilesMatch "^(wp-login.php|xmlrpc.php)$">
  Require all denied
  Redirect gone /
</FilesMatch>

Alternative Apache method:

# Return 410 Gone for wp-login.php and xmlrpc.php
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/(wp-login.php|xmlrpc.php)$ [NC]
RewriteRule ^ - [G,L]

Nginx

# Return 410 Gone for wp-login.php and xmlrpc.php
location ~* ^/(wp-login.php|xmlrpc.php)$ {
    return 410;
}

LiteSpeed

LiteSpeed supports Apache-style .htaccess rules, so use the Apache snippets above.

3. Save and apply changes

After adding the code:

  • For Apache or LiteSpeed, save the .htaccess file in your WordPress root directory.
  • For Nginx, add the snippet to your server block configuration file (e.g., /etc/nginx/sites-available/your-site.conf).
  • Reload or restart your web server:
# Apache
sudo systemctl reload apache2

# Nginx
sudo systemctl reload nginx

# LiteSpeed (depends on setup, often via control panel)

4. Test the response

Use curl or a browser to verify the 410 response:

curl -I https://yourdomain.com/wp-login.php
HTTP/1.1 410 Gone

curl -I https://yourdomain.com/xmlrpc.php
HTTP/1.1 410 Gone

If you see 410 Gone, the configuration works correctly.

Common pitfalls

  • Incorrect file placement: Apache .htaccess must be in the WordPress root directory.
  • Conflicting rules: Other rewrite rules or security plugins may override or conflict with these directives.
  • Server caching: Some hosts use aggressive caching; clear caches after changes.
  • Access needed: If you still need legitimate access to wp-login.php (e.g., for admins), consider restricting by IP instead of serving 410.
  • Control panel overrides: Some managed hosts restrict direct config edits; check with your provider.

Works on

Web Server Supported Notes
Apache Yes Use .htaccess or main config files
Nginx Yes Requires editing server block config
LiteSpeed Yes Supports Apache-style .htaccess rules
cPanel Yes Access .htaccess via File Manager or FTP
Plesk Yes Supports Apache and Nginx config editing

FAQ

1. Will serving 410 break my login or XML-RPC functionality?

Yes, if you or your users rely on wp-login.php or xmlrpc.php, serving 410 will block access. Use this only if you have alternative login methods or have disabled XML-RPC.

2. Can I serve 403 Forbidden instead of 410 Gone?

Yes, 403 is common for blocking access, but 410 explicitly signals the resource is permanently gone, which…

Speed & Security

Disable emojis and embeds to cut requests

Posted on August 19, 2025 By Admin No Comments on Disable emojis and embeds to cut requests

Disable Emojis and Embeds to Cut Requests in WordPress

WordPress loads emoji and embed scripts by default on every page, which adds extra HTTP requests and can slow down your site. Disabling these features reduces unnecessary resource loading, improving page speed and overall performance. This tutorial shows you how to disable emojis and embeds in WordPress quickly and safely.

Quick Fix: Disable Emojis and Embeds in WordPress

  1. Add code snippets to your theme’s functions.php file or a site-specific plugin.
  2. Clear any caching plugins or server caches.
  3. Test your site to confirm emoji and embed scripts are no longer loading.

Why This Happens

WordPress includes built-in support for emojis and oEmbed content (like YouTube videos, Tweets, etc.) by default. This support loads JavaScript and CSS files on every page:

  • Emojis: WordPress loads wp-emoji-release.min.js and related styles to render emojis consistently across browsers.
  • Embeds: WordPress loads wp-embed.min.js to enable embedding content from other sites and to allow your content to be embedded elsewhere.

While useful for many sites, these scripts add extra HTTP requests and increase page size, which can slow down your site, especially on mobile or slow connections.

Step-by-step: Disable Emojis and Embeds in WordPress

Follow these steps to remove emoji and embed scripts from your WordPress site:

  1. Access your theme’s functions.php file or create a site-specific plugin for custom code.
  2. Add the following code snippet:
<?php
// Disable emojis
function disable_wp_emojicons() {
    // Remove emoji scripts and styles
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
    remove_action( 'admin_print_styles', 'print_emoji_styles' );

    // Remove from TinyMCE editor
    add_filter( 'tiny_mce_plugins', 'disable_emojicons_tinymce' );

    // Remove emoji CDN hostname from DNS prefetching hints
    add_filter( 'emoji_svg_url', '__return_false' );
}
add_action( 'init', 'disable_wp_emojicons' );

function disable_emojicons_tinymce( $plugins ) {
    if ( is_array( $plugins ) ) {
        return array_diff( $plugins, array( 'wpemoji' ) );
    }
    return array();
}

// Disable embeds
function disable_wp_embeds() {
    // Remove the REST API endpoint
    remove_action( 'rest_api_init', 'wp_oembed_register_route' );

    // Turn off oEmbed auto discovery
    add_filter( 'embed_oembed_discover', '__return_false' );

    // Remove oEmbed-specific JavaScript from front-end and back-end
    remove_action( 'wp_head', 'wp_oembed_add_discovery_links' );
    remove_action( 'wp_head', 'wp_oembed_add_host_js' );

    // Remove TinyMCE embed plugin
    add_filter( 'tiny_mce_plugins', 'disable_embeds_tinymce' );

    // Remove oEmbed result caching
    remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 );
}
add_action( 'init', 'disable_wp_embeds' );

function disable_embeds_tinymce( $plugins ) {
    if ( is_array( $plugins ) ) {
        return array_diff( $plugins, array( 'wpembed' ) );
    }
    return array();
}
?>
  1. Save the file and upload it back to your server (if editing locally).
  2. Clear all caches: If you use caching plugins (e.g., WP Super Cache, W3 Total Cache) or server-level caching, clear those caches to see the changes immediately.
  3. Verify changes: Use your browser’s developer tools (Network tab) to confirm that wp-emoji-release.min.js and wp-embed.min.js are no longer loaded.

Common Pitfalls

  • Editing the wrong file: Always back up your functions.php file before editing. Use a child theme or a site-specific plugin to avoid losing changes during theme updates.
  • Caching issues: Changes might not appear immediately if caching plugins or server caches are active. Clear all caches after applying the code.
  • Plugin conflicts: Some plugins may enqueue emoji or embed scripts independently. You may need to check plugin settings or contact plugin authors.
  • Impact on embeds: Disabling embeds means WordPress won’t automatically convert URLs into embedded content. Use this only if you don’t rely on oEmbed functionality.

Works on

Environment Compatibility
Web Servers Apache, Nginx, LiteSpeed, IIS
Control Panels cPanel, Plesk, DirectAdmin
WordPress Versions 4.2 and later (all modern versions)
PHP Versions PHP 5.6 and later

FAQ

Q1: Will disabling emojis break my site’s content?
A1: No, disabling emojis only stops WordPress from loading extra emoji scripts. Emojis will still display using native browser support but may look different on older browsers.
Q2: Can I disable only emojis or only embeds?
A2: Yes. You can remove either the emoji or embed code blocks separately from your functions.php file if you want to disable one but keep the other.
Q3: Will disabling embeds affect Gutenberg blocks?
A3: Yes, disabling embeds removes automatic embed discovery and some embed-related blocks. If you rely heavily on Gutenberg embeds, consider leaving this enabled.
Q4: Is there a plugin to disable emojis and embeds?
A4: Yes, plugins like “Disable Emojis
…
Speed & Security

Preload fonts and critical CSS in WordPress

Posted on August 19, 2025 By Admin No Comments on Preload fonts and critical CSS in WordPress

Preload Fonts and Critical CSS in WordPress

Preloading fonts and critical CSS in WordPress improves your website’s loading speed and user experience by instructing browsers to fetch these essential resources early. This reduces render-blocking delays and prevents flash of unstyled text (FOUT), making your site appear faster and smoother.

Quick Fix: How to Preload Fonts and Critical CSS in WordPress

  1. Identify the fonts and critical CSS files your site uses.
  2. Add <link rel="preload"> tags for fonts and critical CSS in your theme’s functions.php or via a plugin.
  3. Ensure proper as attributes and crossorigin settings for fonts.
  4. Test your site with tools like Google PageSpeed Insights to confirm preloading works.

Why This Happens

By default, browsers discover fonts and CSS files during HTML parsing, which can delay their download and block rendering. Fonts especially can cause a flash of invisible or unstyled text if not loaded early. Critical CSS controls the initial page layout and styling; if delayed, users see unstyled content or layout shifts. Preloading tells browsers to prioritize these resources, reducing delays and improving perceived performance.

Requirements

  • Access to your WordPress theme’s functions.php file or a site-specific plugin.
  • Basic knowledge of HTML and WordPress theme development.
  • Understanding of your site’s fonts and CSS files (check browser DevTools).

Step-by-step: Preload Fonts and Critical CSS in WordPress

  1. Identify Fonts and Critical CSS Files
    Use your browser’s Developer Tools (Network tab) to find font files (e.g., .woff2, .woff) and the CSS file(s) containing critical styles. Critical CSS is usually the minimal CSS needed to render above-the-fold content.
  2. Add Preload Tags for Fonts
    Open your theme’s functions.php file or create a site-specific plugin. Add the following code to insert preload headers for your font files:
    function wp_preload_fonts() {
        echo '<link rel="preload" href="' . get_template_directory_uri() . '/fonts/myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous">' . "n";
    }
    add_action('wp_head', 'wp_preload_fonts');

    Replace myfont.woff2 and path with your actual font file location.

  3. Preload Critical CSS
    If you have a separate critical CSS file, preload it similarly:
    function wp_preload_critical_css() {
        echo '<link rel="preload" href="' . get_template_directory_uri() . '/css/critical.css" as="style">' . "n";
        echo '<link rel="stylesheet" href="' . get_template_directory_uri() . '/css/critical.css">' . "n";
    }
    add_action('wp_head', 'wp_preload_critical_css');

    This preloads the critical CSS and immediately applies it.

  4. Combine Preloads
    You can combine font and critical CSS preloads in one function:
    function wp_preload_assets() {
        // Preload font
        echo '<link rel="preload" href="' . get_template_directory_uri() . '/fonts/myfont.woff2" as="font" type="font/woff2" crossorigin="anonymous">' . "n";
        // Preload critical CSS
        echo '<link rel="preload" href="' . get_template_directory_uri() . '/css/critical.css" as="style">' . "n";
        echo '<link rel="stylesheet" href="' . get_template_directory_uri() . '/css/critical.css">' . "n";
    }
    add_action('wp_head', 'wp_preload_assets');
  5. Test Your Site
    Use Google PageSpeed Insights, WebPageTest, or browser DevTools to verify your fonts and critical CSS are preloaded. Look for rel="preload" tags in the page source and check the Network tab for early loading.

Common Pitfalls

  • Missing crossorigin attribute on fonts: Fonts served from your domain or CDN require crossorigin="anonymous" to avoid CORS issues.
  • Incorrect as attribute: Use as="font" for fonts and as="style" for CSS. Wrong values cause browsers to ignore preloading.
  • Preloading too many files: Only preload critical fonts and CSS to avoid wasting bandwidth and blocking other resources.
  • Not applying critical CSS after preload: Preloading CSS alone does not apply it. You must include a stylesheet link or inline the CSS.
  • Using plugins that conflict: Some optimization plugins may already handle preloading. Check plugin settings to avoid duplication.

Works on

This method works on all major web servers and hosting control panels including:

  • Apache
  • Nginx
  • LiteSpeed
  • cPanel
  • Plesk

Because it uses standard WordPress hooks and HTML tags, it is compatible with almost all WordPress setups.

FAQ

Q: Can I preload Google Fonts in WordPress?
A: Yes, but you must self-host the fonts or use the Google Fonts API preload method carefully. Self-hosting fonts allows you to preload them reliably with rel="preload".
Q: How do I generate critical CSS for my WordPress site?
A: Use tools like CriticalCSS.com, SiteLocity Critical CSS Generator, or plugins like Autoptimize that can extract critical CSS automatically.
Q: Will preloading fonts increase my bandwidth usage?
A: Preloading itself does not increase bandwidth but causes fonts to be fetched earlier. Avoid preloading unnecessary fonts to prevent wasted bandwidth.
Q: Can
…
Speed & Security

Cloudflare cache rules for WordPress (no admin caching)

Posted on August 19, 2025 By Admin No Comments on Cloudflare cache rules for WordPress (no admin caching)

Cloudflare Cache Rules for WordPress (No Admin Caching)

If you use Cloudflare with your WordPress site, you might notice issues when the WordPress admin dashboard or login pages get cached. This can cause outdated content, login problems, or broken admin functionality. The quick fix is to set up Cloudflare cache rules that exclude the WordPress admin area and login pages from caching, ensuring smooth backend operations while still benefiting from caching on the public site.

Quick Fix

  1. Log in to your Cloudflare dashboard.
  2. Navigate to the “Rules” section and select “Page Rules” or “Cache Rules” (depending on your Cloudflare plan).
  3. Create rules to bypass cache for URLs related to WordPress admin and login:
    • example.com/wp-admin/*
    • example.com/wp-login.php*
  4. Set these rules to Bypass Cache or Cache Level: Bypass.
  5. Save and deploy the rules.
  6. Test by logging in and accessing the admin dashboard to confirm no caching issues.

Why This Happens

Cloudflare caches static content by default to speed up your website. However, WordPress admin pages and login screens are dynamic and personalized. If Cloudflare caches these pages, users may see stale content or be unable to log in properly. This happens because Cloudflare does not differentiate between public and admin URLs unless explicitly told to do so. Therefore, you need to create cache rules that exclude admin and login URLs from caching.

Requirements

  • A Cloudflare account with your WordPress site added.
  • Access to the Cloudflare dashboard to create cache or page rules.
  • Basic understanding of WordPress URL structure.

Step-by-Step: Setting Up Cloudflare Cache Rules for WordPress Admin

  1. Log in to Cloudflare at https://dash.cloudflare.com.
  2. Select your domain from the list.
  3. Go to the “Rules” tab in the dashboard sidebar.
  4. Create a new Page Rule or Cache Rule (depending on your Cloudflare plan):
    • Click Create Page Rule or Create Cache Rule.
  5. Enter the URL pattern for the WordPress admin area:
  6. https://example.com/wp-admin/*
  7. Set the rule action to: Cache Level: Bypass or Bypass Cache.
  8. Save and deploy the rule.
  9. Create a second rule for the login page:
  10. https://example.com/wp-login.php*
  11. Set the same bypass cache action.
  12. Save and deploy.
  13. Optional: Add rules to bypass caching for REST API and AJAX calls:
  14. https://example.com/wp-json/*
    https://example.com/admin-ajax.php*
  15. Test your site: Log in and navigate the admin dashboard to confirm no caching issues.

Code Snippets for Cloudflare Cache Rules

Here are the exact URL patterns to use when creating your Cloudflare rules:

URL Pattern Cache Action Purpose
https://example.com/wp-admin/* Bypass Cache Exclude WordPress admin pages
https://example.com/wp-login.php* Bypass Cache Exclude login page
https://example.com/wp-json/* Bypass Cache Exclude REST API requests
https://example.com/admin-ajax.php* Bypass Cache Exclude AJAX requests

Note: Replace example.com with your actual domain.

Common Pitfalls

  • Not using HTTPS in URL patterns: Cloudflare rules are protocol-specific. Use https:// if your site uses SSL.
  • Incorrect wildcard usage: Use * to match any characters after the path. For example, /wp-admin/* matches all admin subpages.
  • Rule order matters: Cloudflare processes rules in order. Place bypass rules above any general caching rules.
  • Forgetting REST API and AJAX: These endpoints are critical for admin functionality and should also be excluded from caching.
  • Not clearing Cloudflare cache after changes: Purge cache to ensure new rules take effect immediately.

Works On

  • Cloudflare CDN (all plans with Page Rules or Cache Rules support)
  • WordPress sites on Apache, Nginx, LiteSpeed, or other web servers
  • Hosting control panels like cPanel, Plesk, or custom setups

FAQ

Q: Can I cache the WordPress admin area safely?
A: No, caching the admin area can cause outdated content and login issues. Always bypass cache for admin URLs.
Q: What happens if I don’t exclude wp-login.php from caching?
You may experience login failures or see cached login pages that prevent proper authentication.
Q: Do I need to exclude REST API and AJAX URLs?
Yes, these endpoints are essential for dynamic admin functions and should not be cached.
Q: How do I clear Cloudflare cache after adding rules?
Go to the “Caching” tab in Cloudflare dashboard and click “
…
Speed & Security

BunnyCDN setup for WordPress (origin shield & query‑string cache)

Posted on August 19, 2025 By Admin No Comments on BunnyCDN setup for WordPress (origin shield & query‑string cache)

BunnyCDN Setup for WordPress (Origin Shield & Query-String Cache)

If you want to speed up your WordPress site globally and reduce server load, BunnyCDN is a reliable, cost-effective CDN solution. However, configuring BunnyCDN properly—especially with origin shield and query-string caching—can be tricky. This guide provides a quick fix and detailed steps to set up BunnyCDN with WordPress, ensuring optimal caching behavior and improved site performance.

Quick Fix: BunnyCDN WordPress Setup with Origin Shield & Query-String Cache

  1. Create a BunnyCDN Pull Zone pointing to your WordPress origin server.
  2. Enable Origin Shield in BunnyCDN dashboard to reduce origin hits.
  3. Configure BunnyCDN to cache query-string parameters correctly.
  4. Set appropriate cache-control headers in WordPress (via .htaccess or functions.php).
  5. Update your WordPress URLs to use the BunnyCDN Pull Zone URL.
  6. Test caching behavior and purge cache when necessary.

Why This Happens

WordPress sites often serve dynamic content with query strings (e.g., ?product_id=123), which many CDNs do not cache by default or cache incorrectly. Without proper query-string caching, users may get stale or incorrect content. Additionally, frequent origin requests can overload your server, especially during traffic spikes.

BunnyCDN’s Origin Shield acts as an additional caching layer between your origin and the CDN edge nodes, reducing origin load. Properly configuring query-string caching ensures that BunnyCDN caches unique versions of pages based on query parameters, improving cache hit ratio and user experience.

Requirements

  • Active BunnyCDN account
  • WordPress site with admin access
  • Access to your web server configuration (Apache, Nginx, or via cPanel/Plesk)
  • Basic knowledge of editing WordPress theme files or .htaccess

Step-by-step BunnyCDN WordPress Setup

1. Create a BunnyCDN Pull Zone

  1. Log in to your BunnyCDN dashboard.
  2. Go to Pull Zones and click Add Pull Zone.
  3. Enter a name (e.g., mywpsite), and set your WordPress site URL as the origin URL.
  4. Click Add Pull Zone and wait for the zone to be created.

2. Enable Origin Shield

  1. In your Pull Zone settings, navigate to the Origin Shield tab.
  2. Enable Origin Shield and select the closest region to your origin server.
  3. Save changes.

3. Configure Query-String Caching

  1. Go to the Cache tab in your Pull Zone settings.
  2. Under Query String Caching, select Cache every unique URL.
  3. Optionally, specify which query parameters to include or exclude.
  4. Save changes.

4. Set Cache-Control Headers in WordPress

To ensure BunnyCDN caches your content correctly, set proper cache-control headers. You can do this via .htaccess (Apache) or via WordPress functions.

Apache (.htaccess) example:

# BEGIN BunnyCDN Cache-Control
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType text/html "access plus 1 hour"
  ExpiresByType image/jpeg "access plus 1 month"
  ExpiresByType image/png "access plus 1 month"
  ExpiresByType text/css "access plus 1 week"
  ExpiresByType application/javascript "access plus 1 week"
</IfModule>

<IfModule mod_headers.c>
  Header set Cache-Control "public, max-age=3600"
</IfModule>
# END BunnyCDN Cache-Control

WordPress functions.php example:

function add_cache_control_headers() {
    if (is_admin()) return;
    header('Cache-Control: public, max-age=3600');
}
add_action('send_headers', 'add_cache_control_headers');

5. Replace URLs in WordPress to Use BunnyCDN

Update your WordPress URLs to serve static assets (images, CSS, JS) via BunnyCDN.

  • Use a plugin like Better Search Replace to replace URLs in your database from https://yourdomain.com/wp-content/ to https://yourpullzone.b-cdn.net/wp-content/.
  • Alternatively, use the WP Rocket or W3 Total Cache plugins to rewrite URLs for static files.

6. Test and Purge Cache

  1. Visit your site and inspect network requests to verify assets load from BunnyCDN URL.
  2. Use BunnyCDN’s cache control headers checker or browser dev tools to confirm caching.
  3. If you update content, purge BunnyCDN cache from the dashboard or via API.

Common Pitfalls

  • Not enabling query-string caching: Dynamic pages may serve stale or incorrect content.
  • Incorrect cache-control headers: BunnyCDN may not cache content or cache it too long.
  • Forgetting to update URLs: Static assets won’t load from BunnyCDN, missing performance benefits.
  • Origin Shield region mismatch: Selecting a distant region can increase latency.
  • Plugin conflicts: Some caching or security plugins may interfere with headers or CDN URLs.

Works on

Environment Notes
Apache Supports .htaccess cache headers and URL rewrites.
Nginx Requires manual config for cache-control headers; BunnyCDN works seamlessly.
LiteSpeed Compatible with .htaccess and cache headers.
cPanel / P
…
Speed & Security

Reduce TTFB on budget hosting (OPcache + object cache)

Posted on August 19, 2025 By Admin No Comments on Reduce TTFB on budget hosting (OPcache + object cache)

Reduce TTFB on Budget Hosting (OPcache + Object Cache)

Time To First Byte (TTFB) is a critical performance metric that measures how long it takes for a user’s browser to receive the first byte of data from your server. On budget WordPress hosting, TTFB can often be slow due to limited server resources. This tutorial shows you how to reduce TTFB effectively by enabling OPcache and an object cache, improving your site’s responsiveness without upgrading your hosting plan.

Quick Fix: Enable OPcache and Object Cache

  1. Verify your hosting supports PHP OPcache and enable it in your PHP configuration.
  2. Install and configure a persistent object cache like Redis or Memcached.
  3. Integrate the object cache with WordPress using a suitable plugin.
  4. Test your site’s TTFB before and after to confirm improvements.

Why This Happens

Budget hosting environments typically share resources among many users, leading to slower PHP execution and database queries. WordPress dynamically generates pages by running PHP scripts and querying the database on each request, which increases TTFB.

OPcache caches compiled PHP bytecode, so PHP scripts don’t need to be recompiled on every request, reducing CPU load and execution time.

Object caching stores database query results and other expensive computations in memory, allowing WordPress to serve data faster without repeated database hits.

Combining OPcache with a persistent object cache significantly reduces backend processing time, lowering TTFB even on limited hosting.

Requirements

  • Budget WordPress hosting with PHP 7.4 or higher (PHP 8.x preferred).
  • Access to PHP configuration (php.ini or hosting control panel).
  • Redis or Memcached service available on your server or via your hosting provider.
  • Ability to install WordPress plugins.

Step-by-step Guide

1. Enable OPcache in PHP

Check if OPcache is enabled by creating a phpinfo.php file in your WordPress root directory:

<?php
phpinfo();
?>

Access it via your browser (e.g., https://yourdomain.com/phpinfo.php) and look for the Zend OPcache section.

If OPcache is disabled, enable it by editing your php.ini file or using your hosting control panel’s PHP settings. Add or update these lines:

opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.revalidate_freq=2
opcache.validate_timestamps=1

Restart your web server or PHP-FPM process if you have control over it.

2. Install Redis or Memcached

Check if your hosting provider supports Redis or Memcached. If yes, enable the service via your control panel or request support.

If you have SSH access and permission, install Redis (example for Ubuntu):

sudo apt update
sudo apt install redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server

For Memcached:

sudo apt update
sudo apt install memcached
sudo systemctl enable memcached
sudo systemctl start memcached

3. Install and Configure Object Cache Plugin in WordPress

Use a plugin to connect WordPress with Redis or Memcached. Popular options:

  • Redis Object Cache (for Redis)
  • Memcached Redux (for Memcached)

Example: Installing Redis Object Cache

  1. Go to Plugins > Add New in your WordPress dashboard.
  2. Search for Redis Object Cache and install it.
  3. Activate the plugin.
  4. Go to Settings > Redis and click Enable Object Cache.

4. Verify Object Cache is Working

Use the plugin’s status page or install the Query Monitor plugin to check if object caching is active and reducing database queries.

5. Test TTFB Improvement

Use tools like GTmetrix, Pingdom, or WebPageTest to measure TTFB before and after enabling caching.

Common Pitfalls

  • OPcache not enabled: Some shared hosts disable OPcache by default. Confirm with your provider.
  • Redis/Memcached not available: Budget hosts may not support these services or restrict access.
  • Plugin conflicts: Object cache plugins can conflict with other caching or optimization plugins.
  • Incorrect configuration: Ensure Redis/Memcached connection details match your server setup.
  • Not clearing cache after changes: Always flush caches after plugin or theme updates.

Works on

Server Control Panel Cache Support
Apache, Nginx, LiteSpeed cPanel, Plesk, DirectAdmin PHP OPcache, Redis, Memcached

FAQ

Q: Can I enable OPcache on any shared hosting?
A: Not always. Many budget hosts enable OPcache by default, but some restrict access. Check with your hosting provider.
Q: Is Redis or Memcached better for object caching?
A: Both are effective. Redis offers more features and persistence, while Memcached is simpler. Use whichever your host supports.
Q: Will enabling these caches reduce my database size?
A: No, caching reduces query load and speeds up response times but does not affect database size.
Q: How often should I clear OPcache and object
…
Speed & Security

Best HTTP security headers for WordPress (with examples)

Posted on August 19, 2025 By Admin No Comments on Best HTTP security headers for WordPress (with examples)

Best HTTP Security Headers for WordPress (with Examples)

WordPress security headers are essential HTTP response headers that help protect your website from common web vulnerabilities. Adding the right security headers can prevent attacks like cross-site scripting (XSS), clickjacking, and data injection, improving your site’s overall security posture. This guide explains the best HTTP security headers for WordPress, why they matter, and how to implement them effectively.

Quick Fix: Add These Essential WordPress Security Headers

  1. Content-Security-Policy (CSP): Controls which resources the browser can load.
  2. Strict-Transport-Security (HSTS): Enforces HTTPS connections.
  3. X-Frame-Options: Prevents clickjacking by controlling iframe embedding.
  4. X-Content-Type-Options: Stops MIME type sniffing.
  5. Referrer-Policy: Controls how much referrer information is sent.
  6. Permissions-Policy: Restricts access to browser features.
  7. Expect-CT: Enforces Certificate Transparency to prevent misissued certificates.

Adding these headers to your WordPress site’s server configuration or via plugins will significantly improve your website’s security.

Why This Happens: The Need for WordPress Security Headers

By default, WordPress does not send many HTTP security headers. This leaves your site vulnerable to:

  • Cross-site scripting (XSS): Malicious scripts injected into your pages.
  • Clickjacking: Attackers embedding your site in iframes to trick users.
  • Man-in-the-middle attacks: Without HTTPS enforcement, data can be intercepted.
  • MIME sniffing: Browsers guessing content types, potentially executing malicious files.
  • Data leakage: Referrer headers exposing sensitive URLs.

Security headers instruct browsers on how to handle your site’s content safely, reducing these risks.

Step-by-Step: How to Implement WordPress Security Headers

Depending on your server environment, you can add security headers via your web server configuration or WordPress plugins. Below are examples for Apache, Nginx, and a PHP snippet for WordPress.

1. Apache (.htaccess) Configuration

# Content Security Policy
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';"

# HTTP Strict Transport Security (HSTS)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

# X-Frame-Options to prevent clickjacking
Header set X-Frame-Options "SAMEORIGIN"

# Prevent MIME sniffing
Header set X-Content-Type-Options "nosniff"

# Referrer Policy
Header set Referrer-Policy "no-referrer-when-downgrade"

# Permissions Policy (formerly Feature-Policy)
Header set Permissions-Policy "geolocation=(), microphone=(), camera=()"

# Expect-CT for Certificate Transparency
Header set Expect-CT "max-age=86400, enforce"

2. Nginx Configuration

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';" always;

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

add_header X-Frame-Options "SAMEORIGIN" always;

add_header X-Content-Type-Options "nosniff" always;

add_header Referrer-Policy "no-referrer-when-downgrade" always;

add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

add_header Expect-CT "max-age=86400, enforce" always;

3. WordPress PHP Snippet (functions.php or custom plugin)

function add_security_headers() {
    header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://trusted.cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';");
    header("Strict-Transport-Security: max-age=31536000; includeSubDomains; preload");
    header("X-Frame-Options: SAMEORIGIN");
    header("X-Content-Type-Options: nosniff");
    header("Referrer-Policy: no-referrer-when-downgrade");
    header("Permissions-Policy: geolocation=(), microphone=(), camera=()");
    header("Expect-CT: max-age=86400, enforce");
}
add_action('send_headers', 'add_security_headers');

Note: Adjust the Content-Security-Policy directives to match your site’s resources and trusted domains.

Verification: How to Check Your WordPress Security Headers

After implementing the headers, verify they are active using these methods:

  • Browser Developer Tools: Open your site, press F12, go to the Network tab, reload, and inspect the response headers.
  • Online Tools: Use services like securityheaders.com or Mozilla Observatory.
  • Command Line: Run curl -I https://yourdomain.com and look for the security headers in the output.

Works On

Environment Notes
Apache Modify .htaccess or server config files.
Nginx Edit server block configuration files.
LiteSpeed Compatible with Apache directives in .htaccess.
cPanel / Plesk Use built-in editors for Apache/Nginx configs or add PHP snippets.
WordPress Plugins Plugins like “HTTP Headers” or
…
Speed & Security

Block bad bots with .htaccess (copy/paste rules)

Posted on August 19, 2025 By Admin No Comments on Block bad bots with .htaccess (copy/paste rules)

Block Bad Bots with .htaccess (Copy/Paste Rules)

If your WordPress site is suffering from unwanted traffic caused by bad bots—scraping content, spamming forms, or consuming server resources—you can block them efficiently using .htaccess rules. This tutorial provides quick, copy-paste-ready .htaccess snippets to block common bad bots and protect your site.

Quick Fix: Block Bad Bots in .htaccess

  1. Access your WordPress site’s root directory via FTP or hosting file manager.
  2. Open or create the .htaccess file in the root folder.
  3. Copy and paste the provided bad bot blocking rules into the .htaccess file.
  4. Save the file and test your site to ensure it works correctly.

Why This Happens

Bad bots are automated scripts that crawl websites for malicious purposes such as scraping content, spamming, brute forcing login pages, or overloading servers. Unlike good bots (like Googlebot), bad bots ignore robots.txt rules and can cause:

  • High server load and slow site performance
  • Security vulnerabilities through brute force or injection attacks
  • Content theft and SEO penalties

Blocking these bots at the server level using .htaccess is an effective way to reduce unwanted traffic before it reaches WordPress.

Requirements

  • Apache web server with mod_rewrite enabled
  • Access to your site’s root .htaccess file
  • Basic knowledge of FTP or hosting file manager
  • Backup of your current .htaccess file before editing

Step-by-step: Block Bad Bots with .htaccess

  1. Backup your current .htaccess file. Always keep a copy before making changes.
  2. Access your site’s root directory. Use FTP or your hosting control panel’s file manager.
  3. Open the .htaccess file. If it doesn’t exist, create a new plain text file named .htaccess.
  4. Paste the following code at the top of the file, before WordPress rules:
# BEGIN Block Bad Bots
<IfModule mod_rewrite.c>
RewriteEngine On

# Block bad bots by User-Agent
RewriteCond %{HTTP_USER_AGENT} ^.*(AhrefsBot|SemrushBot|MJ12bot|BLEXBot|DotBot|Screaming Frog|YandexBot|Exabot|Ezooms|Sogou).* [NC]
RewriteRule .* - [F,L]

# Block bad bots by Referer (optional)
# RewriteCond %{HTTP_REFERER} ^.*(spamdomain1.com|spamdomain2.net).* [NC]
# RewriteRule .* - [F,L]

</IfModule>
# END Block Bad Bots
  1. Save the file. Upload it back if using FTP.
  2. Test your site. Visit your site to ensure it loads correctly.
  3. Verify blocking. Use online tools or curl commands to simulate bad bot User-Agents and confirm they receive a 403 Forbidden response.

Common Pitfalls

  • Placing rules after WordPress block: Always add bad bot rules before the WordPress section in .htaccess to ensure they take effect.
  • Typos in User-Agent names: User-Agent strings are case-insensitive but must be spelled correctly to match.
  • Blocking legitimate bots: Avoid blocking well-known good bots like Googlebot or Bingbot to prevent SEO issues.
  • Server without mod_rewrite: These rules require Apache’s mod_rewrite module; they won’t work on Nginx or if mod_rewrite is disabled.
  • Overblocking: Be cautious with broad patterns to avoid blocking real users or services.

Works on

Server Compatibility
Apache Fully compatible with mod_rewrite enabled
Nginx Not compatible (requires different config)
LiteSpeed Compatible (supports Apache .htaccess rules)
cPanel / Plesk Compatible (access .htaccess via file manager or FTP)

FAQ

Q1: How do I find out which bots are bad?
A: You can check your server logs or use analytics tools to identify suspicious User-Agent strings. Common bad bots include AhrefsBot, SemrushBot, MJ12bot, and others known for scraping or spamming.
Q2: Can I block bad bots using plugins instead of .htaccess?
A: Yes, there are WordPress plugins that block bad bots, but .htaccess blocking is faster and reduces server load by stopping requests early.
Q3: What if I accidentally block a good bot?
A: Remove or adjust the User-Agent pattern from the .htaccess file and test again. Always verify User-Agent strings before blocking.
Q4: Will blocking bad bots improve my SEO?
A: Indirectly yes. Blocking bad bots reduces server load and prevents content scraping, which can protect your SEO rankings.
Q5: Can I block bots by IP instead of User-Agent?
A: Yes, but IP addresses can change frequently. Blocking by User-Agent is more flexible for bad bots that identify themselves.
…
Speed & Security

Disable XML‑RPC in WordPress (and what breaks if you do)

Posted on August 19, 2025 By Admin No Comments on Disable XML‑RPC in WordPress (and what breaks if you do)

Disable XML-RPC in WordPress (and what breaks if you do)

XML-RPC is a remote procedure call protocol used by WordPress to enable communication between your site and external applications. While it offers useful features like remote publishing and mobile app connectivity, it can also be a security risk or a performance bottleneck. This guide explains how to disable XML-RPC in WordPress safely, what functionality you lose by doing so, and how to verify the change.

Quick Fix: How to Disable XML-RPC in WordPress

  1. Add the following code snippet to your theme’s functions.php file or a site-specific plugin to completely disable XML-RPC:
add_filter('xmlrpc_enabled', '__return_false');
  1. Alternatively, block access to the xmlrpc.php file via your web server configuration (Apache or Nginx).

Why This Happens: Understanding XML-RPC and Its Risks

XML-RPC was introduced in WordPress to allow external applications to interact with your site, such as posting content remotely, managing comments, or using mobile apps. However, it has become a common target for brute force attacks and DDoS amplification because it allows multiple authentication attempts in a single request.

Disabling XML-RPC reduces your attack surface and can improve site performance by preventing unnecessary requests. However, some legitimate services and plugins rely on XML-RPC, so disabling it may break certain features.

Step-by-Step: How to Disable XML-RPC in WordPress

Method 1: Disable XML-RPC via WordPress Filter

  1. Access your WordPress site files via FTP, SFTP, or your hosting file manager.
  2. Navigate to wp-content/themes/your-active-theme/ and open functions.php.
  3. Add the following line at the end of the file:
add_filter('xmlrpc_enabled', '__return_false');
  1. Save the file and upload it back if using FTP.
  2. Test your site to ensure it functions normally.

Method 2: Block XML-RPC via Apache (.htaccess)

  1. Open or create the .htaccess file in your WordPress root directory.
  2. Add the following code to block access to xmlrpc.php:
<Files xmlrpc.php>
  Order Deny,Allow
  Deny from all
</Files>
  1. Save and upload the file.

Method 3: Block XML-RPC via Nginx Configuration

  1. Access your Nginx server configuration file for your site (e.g., /etc/nginx/sites-available/your-site.conf).
  2. Add this location block inside the server block:
location = /xmlrpc.php {
  deny all;
  access_log off;
  log_not_found off;
}
  1. Save the file and reload Nginx:
sudo nginx -s reload

Verification: How to Confirm XML-RPC Is Disabled

  1. Use an online XML-RPC tester such as https://xmlrpc.eritreo.it/ to check your site’s XML-RPC endpoint.
  2. Send a POST request to https://yourdomain.com/xmlrpc.php. You should receive a 403 Forbidden or a message indicating XML-RPC is disabled.
  3. Alternatively, run this command from your terminal:
curl -I https://yourdomain.com/xmlrpc.php

The response headers should indicate access is denied or the file is unreachable.

Works on

Environment Compatibility
Apache (with .htaccess) Fully supported
Nginx Fully supported via config block
LiteSpeed Supports .htaccess rules and PHP filters
cPanel Supports all methods, access via file manager or terminal
Plesk Supports all methods, access via file manager or terminal

FAQ

Q1: Will disabling XML-RPC break the WordPress mobile app?
A1: Yes, the official WordPress mobile app relies on XML-RPC to communicate with your site. Disabling it will prevent the app from working properly.
Q2: Can I disable XML-RPC partially instead of completely?
A2: Yes, you can use plugins or custom code to disable specific XML-RPC methods or limit access to trusted IPs instead of disabling it entirely.
Q3: Does disabling XML-RPC improve site security?
A3: Yes, it reduces the attack surface by blocking a common vector for brute force and DDoS attacks.
Q4: Will Jetpack or other plugins stop working if I disable XML-RPC?
A4: Jetpack and some other plugins depend on XML-RPC. Disabling it may cause them to malfunction or lose features.
Q5: Is there a plugin to disable XML-RPC without editing code?
A5: Yes, plugins like “Disable XML-RPC” or security plugins such as Wordfence provide options to disable or restrict XML-RPC easily.
…
Speed & Security

Serve WebP in WordPress (with safe JPEG/PNG fallbacks)

Posted on August 19, 2025 By Admin No Comments on Serve WebP in WordPress (with safe JPEG/PNG fallbacks)

Serve WebP in WordPress (with safe JPEG/PNG fallbacks)

Serving WebP images in WordPress improves site speed and reduces bandwidth by delivering smaller, optimized images. However, not all browsers support WebP, so it’s essential to provide safe JPEG/PNG fallbacks. This tutorial shows you how to configure your WordPress site to serve WebP images with fallback support using .htaccess rules.

Quick Fix: Serve WebP with JPEG/PNG Fallbacks via .htaccess

  1. Generate WebP versions of your images (using a plugin or external tool).
  2. Upload WebP images alongside original JPEG/PNG files in your WordPress uploads folder.
  3. Add the provided .htaccess code snippet to your WordPress root directory.
  4. Test your site in different browsers to confirm WebP images load where supported, and JPEG/PNG fallback loads otherwise.

Why This Happens

WebP is a modern image format offering superior compression compared to JPEG and PNG, resulting in faster page loads. However, older browsers or some niche browsers do not support WebP. Without fallback images, unsupported browsers will fail to display images, breaking your site’s appearance.

WordPress by default does not serve WebP images automatically or provide fallbacks. You must configure your server to detect browser support and serve the appropriate image format. Using .htaccess rewrite rules on Apache servers is a common and efficient method to achieve this without changing your theme or plugins.

Requirements

  • Apache web server with mod_rewrite enabled.
  • Access to your WordPress root directory to edit or add a .htaccess file.
  • WebP versions of your images stored alongside original JPEG/PNG files.
  • Basic familiarity with FTP or file manager to upload files and edit .htaccess.

Step-by-step: Serve WebP with JPEG/PNG Fallbacks in WordPress

  1. Create WebP images: Use a plugin like Imagify, EWWW Image Optimizer, or an external tool to generate WebP versions of your JPEG/PNG images. Ensure WebP files are saved in the same folder as the originals.
  2. Backup your current .htaccess file: Before making changes, download a copy of your existing .htaccess file from your WordPress root directory.
  3. Edit your .htaccess file: Add the following code snippet near the top of your .htaccess file, before the WordPress rules block:
# Serve WebP images with JPEG/PNG fallback
<IfModule mod_rewrite.c>
  RewriteEngine On

  # Check if browser supports WebP
  RewriteCond %{HTTP_ACCEPT} image/webp

  # Check if WebP version of the requested image exists
  RewriteCond %{REQUEST_FILENAME}.webp -f

  # Serve WebP image instead
  RewriteRule ^(wp-content/.+.(jpe?g|png))$ $1.webp [T=image/webp,E=accept:1]
</IfModule>

# Add correct content type for WebP images
<IfModule mod_headers.c>
  <FilesMatch ".webp$">
    Header set Content-Type "image/webp"
  </FilesMatch>
</IfModule>

# Ensure WebP images are served with proper caching
<IfModule mod_expires.c>
  ExpiresByType image/webp "access plus 1 month"
</IfModule>
  1. Save and upload the updated .htaccess file.
  2. Clear your site and browser cache.
  3. Test your site: Open your website in a WebP-supporting browser (Chrome, Firefox, Edge) and verify images are served as WebP (use browser developer tools → Network tab → check image content-type). Then test in a non-WebP browser (Safari older versions, IE) to confirm JPEG/PNG images load instead.

Common Pitfalls

  • WebP files missing: The rewrite rule only works if the WebP version exists. Make sure WebP images are generated and uploaded correctly.
  • mod_rewrite not enabled: The rules require Apache’s mod_rewrite module. Confirm it is enabled on your server.
  • Incorrect .htaccess placement: The .htaccess file must be in your WordPress root directory (where wp-config.php is located).
  • Conflicts with other plugins: Some caching or image optimization plugins may conflict with manual .htaccess rules. Test carefully and disable conflicting plugins if needed.
  • Browser caching: Old cached images may prevent you from seeing changes immediately. Clear cache or test in incognito mode.

Works on

Server Compatibility
Apache Fully supported (with mod_rewrite enabled)
Nginx Not applicable (use Nginx config instead)
LiteSpeed Compatible with Apache .htaccess rules
cPanel / Plesk Supported (edit .htaccess via file manager or FTP)

FAQ

Q: How do I generate WebP images for my existing WordPress media library?
A: Use plugins like Imagify or EWWW Image Optimizer that automatically convert and save WebP versions of your images in the uploads folder.
Q: Will this method slow down my website?
A: No. The rewrite rules are efficient and only redirect requests if a WebP version exists and the browser supports it, improving load times by serving smaller images.
Q: What if my server uses
…
Speed & Security

Posts pagination

1 2 Next

Recent Posts

  • Top WordPress Themes for Blogs in 2025
  • WordPress Admin Panel Trick: Adding ID Field to the Posts Listing
  • Solution previous_posts_link and next_posts_link Not Working
  • Show Top Commentators in WordPress Without a Plugin
  • How to Style Admin Comments in WordPress

Recent Comments

    Archives

    • August 2025

    Categories

    • Admin & Blocks
    • Admin & UI
    • Automation
    • Automation & Plugins
    • Comments
    • Comparisons
    • Database & Revisions
    • Developer Snippets
    • Fixes & Errors
    • Media & Thumbnails
    • Queries & Pagination
    • Security
    • Speed & Security
    • Tips & Tricks
    • WooCommerce How‑tos
    • WordPress Snippets
    • WordPress Themes
    • Terms & Conditions
    • Affiliate Disclosure

    Copyright © 2025 wpcanyon.com.

    Powered by PressBook WordPress theme