Redirect Uploads Folder to Query Vars in WordPress

I’m looking to redirect pdfs documents from the uploads folder to WordPress to prevent unauthorized site visitors from viewing them.

I have used the code provided from this thread How to restrict attachment download to a specific user? and it most definitely works. However, in my plugin, I would like to add the rewrite rule using the WordPress’s Rewrite API, so the rewrite rule will automatically get added to the .htaccess file either on activation or when the rewrite rules are flushed. I want to avoid manually adding it.

The rewrite rule I am looking to add is ^wp-content/uploads/(.*.pdf)$ /index.php?get_file=$1.

/**
* Flushes rewrites if our project rule isn’t yet added.
*/
function wpdocs_flush_rules() {
$rules = get_option( ‘rewrite_rules’ );

if ( ! isset( $rules[‘^wp-content/uploads/(.*.pdf)$’] ) ) {
global $wp_rewrite;
$wp_rewrite->flush_rules();
echo ‘flushed’;
}
}
add_action( ‘wp_loaded’,’wpdocs_flush_rules’ );

/**
* Adds a new rewrite rule.
*
* @param array $rules Existing rewrite rules.
* @return array (Maybe) modified list of rewrites.
*/
function wpdocs_insert_rewrite_rules( $rules ) {
$newrules = array();
$newrules[‘wp-content/uploads/(.*.pdf)$’] = ‘/index.php?get_file=$1’;
return array_merge( $newrules, $rules);
}
add_filter( ‘rewrite_rules_array’,’wpdocs_insert_rewrite_rules’ );

// Adding the id var so that WP recognizes it
function wpdocs_insert_query_vars( $vars ) {
array_push( $vars, ‘get_file’ );
return $vars;
}
add_filter( ‘query_vars’,’wpdocs_insert_query_vars’ );

I even tried using insert_with_markers and add_rewrite_rule( $regex, $query, ‘top’ ). In fact, the rewrite rule was written into the WP_Rewrite object correctly, but just not added to the .htaccess file. When I change the $query to not be related to index.php, it gets added no problem to .htaccess, which of course is not what I want. It seems WordPress is preventing certain rules from being added to the actual .htaccess file.

Thanks for your help!

Read more here:: Redirect Uploads Folder to Query Vars in WordPress

Leave a Reply

Your email address will not be published. Required fields are marked *