Using WordPress ‘got_rewrite’ PHP filter

The got_rewrite WordPress PHP filter checks if Apache and mod_rewrite are present.

Usage

add_filter( 'got_rewrite', 'your_custom_function' );

function your_custom_function( $got_rewrite ) {
    // your custom code here
    return $got_rewrite;
}

Parameters

  • $got_rewrite (bool) – Indicates whether Apache and mod_rewrite are present or not.

More information

See WordPress Developer Resources: got_rewrite

Examples

Force URL rewriting for Nginx

Force URL rewriting for the Nginx server by returning true for the got_rewrite filter.

add_filter( 'got_rewrite', 'force_url_rewriting' );

function force_url_rewriting( $got_rewrite ) {
    // Return true to force URL rewriting
    return true;
}

Disable URL rewriting

Disable URL rewriting by returning false for the got_rewrite filter.

add_filter( 'got_rewrite', 'disable_url_rewriting' );

function disable_url_rewriting( $got_rewrite ) {
    // Return false to disable URL rewriting
    return false;
}

Check for Apache and mod_rewrite

Log a message if Apache and mod_rewrite are present.

add_filter( 'got_rewrite', 'check_apache_mod_rewrite' );

function check_apache_mod_rewrite( $got_rewrite ) {
    // If Apache and mod_rewrite are present, log a message
    if ( $got_rewrite ) {
        error_log( 'Apache and mod_rewrite are present.' );
    }
    return $got_rewrite;
}

Enable URL rewriting for specific conditions

Enable URL rewriting only for specific conditions, such as when a certain plugin is active.

add_filter( 'got_rewrite', 'enable_url_rewriting_conditionally' );

function enable_url_rewriting_conditionally( $got_rewrite ) {
    // Check if a specific plugin is active
    if ( function_exists( 'your_plugin_function' ) ) {
        // Enable URL rewriting if the plugin is active
        return true;
    }
    return $got_rewrite;
}

Change URL rewriting based on environment

Change URL rewriting settings based on the environment, such as enabling URL rewriting on production but disabling it on staging.

add_filter( 'got_rewrite', 'change_url_rewriting_by_environment' );

function change_url_rewriting_by_environment( $got_rewrite ) {
    // Check the environment
    $environment = getenv( 'WP_ENV' );

    // Enable URL rewriting on production
    if ( 'production' === $environment ) {
        return true;
    }
    // Disable URL rewriting on staging
    elseif ( 'staging' === $environment ) {
        return false;
    }
    return $got_rewrite;
}