The got_url_rewrite() WordPress PHP function determines if the server supports URL rewriting.
Usage
$has_rewrite = got_url_rewrite();
Parameters
- None
More information
See WordPress Developer Resources: got_url_rewrite()
Examples
Redirect non-www to www URLs
Check if URL rewriting is available before redirecting non-www URLs to their www counterparts.
if (got_url_rewrite()) {
add_action('init', 'redirect_nonwww_to_www');
}
function redirect_nonwww_to_www() {
if (strpos($_SERVER['HTTP_HOST'], 'www.') === false) {
wp_redirect('https://www.' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], 301);
exit;
}
}
Add custom rewrite rules
Add custom rewrite rules for a custom post type if URL rewriting is supported.
if (got_url_rewrite()) {
add_action('init', 'add_custom_rewrite_rules');
}
function add_custom_rewrite_rules() {
add_rewrite_rule('^custom_post_type/([a-zA-Z0-9]+)/?', 'index.php?custom_post_type=$matches[1]', 'top');
}
Show a notice if URL rewriting is not supported
Inform the user if URL rewriting is not available on their server.
add_action('admin_notices', 'check_url_rewrite_support');
function check_url_rewrite_support() {
if (!got_url_rewrite()) {
echo '<div class="notice notice-error is-dismissible"><p>URL rewriting is not supported on your server. Please contact your hosting provider.</p></div>';
}
}
Disable a plugin if URL rewriting is not supported
Deactivate a plugin that relies on URL rewriting if it’s not available.
add_action('admin_init', 'deactivate_plugin_if_no_rewrite');
function deactivate_plugin_if_no_rewrite() {
if (!got_url_rewrite()) {
deactivate_plugins('your-plugin/your-plugin.php');
wp_die('The plugin "Your Plugin" has been deactivated because URL rewriting is not supported on your server.');
}
}
Choose the appropriate sitemap URL structure
Generate sitemap URLs based on whether the server supports URL rewriting.
function get_sitemap_url($post_id) {
if (got_url_rewrite()) {
return home_url('/sitemap-' . $post_id . '.xml');
} else {
return home_url('/?sitemap=' . $post_id);
}
}