WP Safe htaccess Manager un plugin WordPress

WP Safe htaccess Manager
WP Safe htaccess Manager

WP Safe HTAccess Manager: Documentación Oficial

Introducción: La Necesidad del Usuario y el Propósito del Plugin

La seguridad web y la optimización del rendimiento a menudo requieren modificar el archivo .htaccess, un potente archivo de configuración central en servidores Apache. Sin embargo, este archivo es notoriamente sensible a errores de sintaxis. Un solo carácter mal colocado puede resultar en un Error 500 (Internal Server Error), dejando todo tu sitio web inaccesible, a veces incluso para ti.

Los usuarios necesitan una forma rápida, segura y auditable de implementar reglas de seguridad críticas (como bloquear XML-RPC o añadir cabeceras de seguridad) sin el miedo constante de romper su sitio.

Propósito del Plugin

WP Safe HTAccess Manager resuelve este problema al proporcionar una interfaz simple y controlada dentro de WordPress. Su propósito principal es:

  1. Garantizar la Estabilidad: Cada cambio se somete a un «Atomic Stability Test» simulado. Si la escritura falla (por errores de permisos o sintaxis potencial), el plugin no guarda la configuración en la base de datos de WordPress y te alerta, actuando como un mecanismo de prevención de errores 500.
  2. Ofrecer Reglas Clave: Proporciona un conjunto de plantillas predefinidas para las reglas de seguridad más comunes y recomendadas.
  3. Mantener la Auditabilidad: Todas las reglas aplicadas se insertan con delimitadores, marcas de tiempo y atribución, facilitando la depuración futura y el seguimiento de cambios.

Guía de Instalación y Uso

1. Instalación

  1. Subir el Archivo: Sube el archivo wp-safe-htaccess-manager.php (o la carpeta del plugin, si está empaquetado) al directorio wp-content/plugins/.
  2. Activar: Ve a Plugins en tu panel de WordPress y haz clic en Activar para WP Safe HTAccess Manager.
  3. Acceso: El menú de configuración aparecerá en Ajustes HTAccess Shield.

2. Uso (Aplicando Reglas de Seguridad)

El panel de administración está dividido en secciones claras:

1. Suggested Security Rules (Reglas Sugeridas)

Esta sección contiene plantillas de reglas de seguridad comunes.

  • Para Activar: Marca el checkbox junto al nombre de la regla (ejemplo: «Protect wp-config.php»).
  • Para Desactivar: Desmarca el checkbox.
  • El estado Active/Inactive refleja la configuración que será guardada.

2. Custom Rules (Reglas Personalizadas)

Si necesitas añadir directivas Apache personalizadas no cubiertas por las plantillas, puedes pegarlas en este campo de texto.

  • Importante: Introduce solo directivas válidas de Apache. ¡Recuerda que estas también serán probadas por el «Atomic Test»!

3. Execute Atomic Test (Ejecutar Prueba Atómica)

Este es el paso crucial:

  1. Una vez que hayas seleccionado tus reglas y añadido código personalizado, haz clic en el botón principal: ? Execute Atomic Test and Apply Changes to .htaccess.
  2. Resultado Exitoso: Si la operación es exitosa (la escritura del archivo funciona), recibirás un mensaje de «Changes applied successfully! Atomic Test passed.» y tus nuevas reglas aparecerán en el archivo .htaccess con sus marcas de tiempo.
  3. Resultado Fallido: Si la operación falla (generalmente por permisos de archivo), recibirás un mensaje de error y tu archivo .htaccess no se modificará, previniendo un error 500.

Documentación Técnica

Flujo de Ejecución y Atomic Test

El plugin utiliza el principio POST-Redirect-GET (PRG) para manejar el envío de formularios y ejecuta la lógica de guardado en el hook admin_init.

  1. Manejo de Formulario (handle_form_submission):
    • Verifica la capacidad del usuario (manage_options).
    • Nonce Check: Realiza una verificación estricta del Nonce (shield_apply_changes) para proteger contra ataques CSRF. Un fallo detiene el proceso y muestra el error «Security check failed.».
    • Recopila la configuración de la base de datos.
  2. Generación de Contenido (generate_rules_block_content):
    • Esta función toma las reglas activas y el código personalizado.
    • Crea una línea de auditoría: # Added by WP Safe HTAccess Manager on [Fecha y Hora].
    • Compila todas las reglas activas en un bloque de texto único, incluyendo la línea de auditoría sobre cada regla.
  3. Escritura Segura (El «Atomic Test» Simulado):
    • El plugin utiliza la función central de WordPress: insert_with_markers( $htaccess_path, $marker, $rules_to_insert ).
    • Esta función busca el marcador (# BEGIN WP SHIELD RULES) y reemplaza todo el contenido delimitado con las nuevas reglas.
    • El «Atomic Test» es simulado: Si insert_with_markers devuelve TRUE, se considera que el test de estabilidad pasó, y la configuración se guarda en la base de datos (update_option). Si devuelve FALSE (generalmente por permisos de archivo), el test falla, no se modifica la base de datos, y el usuario recibe el mensaje de error.

 

Estructura de Marcadores en .htaccess

Las reglas del plugin siempre se insertan entre los siguientes delimitadores, asegurando que no interfieran con las reglas de WordPress u otras reglas de plugins (como caché):

# BEGIN WP SHIELD RULES
# — Rule: Block XML-RPC —
# Added by WP Safe HTAccess Manager on 2025-10-01 20:25:28.
<Files xmlrpc.php>
Order Deny,Allow
Deny from all
</Files>

# — Rule: Custom HTAccess Code —
# Added by WP Safe HTAccess Manager on 2025-10-01 20:25:28.
# (Tu código personalizado aquí)

# END WP SHIELD RULES

Opciones de WordPress Utilizadas

El plugin guarda su estado y configuración en la tabla wp_options:

Clave (Option Key) Uso Tipo de Dato
wp_safe_htaccess_rules Array asociativo ['rule_key'] => 1 o 0 para las reglas predefinidas. array
wp_safe_htaccess_custom_code El código HTAccess personalizado ingresado por el usuario. string
wp_shield_messages Utilizado como transient para mostrar mensajes de éxito o error tras la redirección. transient

Puede descargarlo desde:

WP Safe htaccess Manager

Si requiere soporte acerca del plugin por favor escríba desde aquí

 

English Language:

WP Safe HTAccess Manager: Official Documentation

Introduction: User Needs and Plugin Purpose

Web security and performance optimization often require modifying the .php file .htaccess, a powerful, central configuration file on Apache servers. However, this file is notoriously sensitive to syntax errors . A single misplaced character can result in a 500 Internal Server Error , rendering your entire website inaccessible—sometimes even to you.

Users need a fast, secure, and auditable way to implement critical security rules (such as blocking XML-RPC or adding security headers) without the constant fear of breaking their site.

Purpose of the Plugin

WP Safe HTAccess Manager solves this problem by providing a simple, controlled interface within WordPress. Its main purpose is to:

  1. Ensure Stability: Each change is subjected to a simulated «Atomic Stability Test .» If the write fails (due to permission or potential syntax errors), the plugin doesn’t save the configuration to the WordPress database and alerts you, acting as a 500 error prevention mechanism .
  2. Offer Key Rules: Provides a set of predefined templates for the most common and recommended security rules.
  3. Maintain Auditability: All applied rules are embedded with delimiters, timestamps, and attribution , facilitating future debugging and change tracking.

Installation and User Guide

1. Installation

  1. Upload File: Upload the file wp-safe-htaccess-manager.php(or plugin folder, if packaged) to the wp-content/plugins/.
  2. Activate: Go to Plugins in your WordPress dashboard and click Activate for WP Safe HTAccess Manager .
  3. Access: The settings menu will appear under Settings  HTAccess Shield .

2. Use (Applying Safety Rules)

The admin panel is divided into clear sections:

1. Suggested Security Rules

This section contains common security rule templates.

  • To Enable: Check the box next to the rule name (example: “Protect wp-config.php”).
  • To Disable: Uncheck the checkbox .
  • The Active/Inactive state reflects the configuration that will be saved.

2. Custom Rules

If you need to add custom Apache directives not covered by the templates, you can paste them into this text field.

  • Important: Enter only valid Apache directives. Remember that these will also be tested by the Atomic Test!

3. Execute Atomic Test

This is the crucial step:

  1. Once you’ve selected your rules and added custom code, click the main button: ? Execute Atomic Test and Apply Changes to .htaccess .
  2. Successful Result: If the operation is successful (writing to the file works), you will receive a message saying “Changes applied successfully! Atomic Test passed.” and your new rules will appear in the file .htaccesswith their timestamps.
  3. Failed Result: If the operation fails (usually due to file permissions), you will receive an error message and your file .htaccesswill not be modified , preventing a 500 error.

Technical Documentation

Execution Flow and Atomic Test

The plugin uses the POST-Redirect-GET (PRG) principle to handle form submissions and executes the save logic in the hook admin_init .

  1. Form Handling ( handle_form_submission) :
    • Check the user capacity ( manage_options).
    • Nonce Check: Performs strict nonce verification ( shield_apply_changes) to protect against CSRF attacks. Failure to do so will stop the process and display the error «Security check failed.»
    • Collects the database configuration.
  2. Content Generation ( generate_rules_block_content) :
    • This function takes the active rules and custom code.
    • Create an audit line: # Added by WP Safe HTAccess Manager on [Fecha y Hora].
    • Compiles all active rules into a single block of text, including the audit trail for each rule.
  3. Secure Writing (The Simulated «Atomic Test») :
    • The plugin uses the core WordPress function: insert_with_markers( $htaccess_path, $marker, $rules_to_insert ).
    • This function finds the marker ( # BEGIN WP SHIELD RULES) and replaces all the delimited content with the new rules.
    • The Atomic Test is simulated: If insert_with_markersit returns , the stability testTRUE is considered passed, and the configuration is saved to the database ( ). If it returns (usually due to file permissions), the test fails, the database is not modified, and the user receives the error message.update_optionFALSE

 

Structure of Markers in.htaccess

Plugin rules are always inserted between the following delimiters, ensuring they do not interfere with WordPress rules or other plugin rules (such as caching):

# BEGIN WP SHIELD RULES
# — Rule: Block XML-RPC —
# Added by WP Safe HTAccess Manager on 2025-10-01 20:25:28.
<Files xmlrpc.php>
Order Deny,Allow
Deny from all
</Files>

# — Rule: Custom HTAccess Code —
# Added by WP Safe HTAccess Manager on 2025-10-01 20:25:28.
# (Tu código personalizado aquí)

# END WP SHIELD RULES

WordPress Options Used

The plugin saves its state and configuration in the table wp_options:

Clave (Option Key) Use Data Type
wp_safe_htaccess_rules Associative array ['rule_key'] => 1 o 0for predefined rules. array
wp_safe_htaccess_custom_code The custom HTAccess code entered by the user. string
wp_shield_messages Used transientto display success or error messages after redirection. transient

You can download it from:
WP Safe htaccess Manager
If you need support regarding the plugin, please write here

Publicado el 01 Oct, 2025

Compartir en FacebookCompartir en XCompartir en LinkedinCompartir en PinterestCompartir en Whatsapp