How to Manage and Write .htaccess Files in WordPress

How to Manage and Write .htaccess Files in WordPress

Before WordPress handles an incoming request, your server processes it in a number of ways checking for malicious sources, spam etc. After that, it’s subject to a bunch of rules contained in a special file known as .htaccess. This is located in the root folder of your website. It’s hidden by default and so when you access your website via an FTP program, you have to make sure that you’ve turned on the setting to make hidden files visible.

.htaccess files have a standard syntax, using which you can perform fairly complex operations such as rerouting, rewriting URLs, setting all kinds of headers etc. .htaccess files are the backbone for many websites. Without them, most of what we see on the web would be rendered unusable. WordPress provides us with the necessary tools to manipulate .htaccess files and rules. Using a combination of raw .htaccess manipulation and specialized functions to specify rewrite rules, plug-in and theme developers have complete control over their .htaccess files.

.htaccess File Location

Websites generally have a single .htaccess file in the root location of their web directory. This means that the “public_html” folder that you see when you login via FTP has an .htaccess file that dictates how to process incoming requests for any file in its scope.

However, individual folders can have their own .htaccess files specifying more local rules that take precedence over the general ones above it. This way, you can have extremely fine control over how the files in any particular folder or its subdirectories are treated. Let’s say for example that you have a WordPress installation located in a sub directory instead of the root of your server. Placing an .htaccess file within the top level of that sub directory will affect your entire WordPress installation and the rules within it will overwrite the rules present in the general root directory.

We can check the existence of this .htaccess file within the WordPress code itself. For example, the “misc.php” core WordPress file located in “wp-admin/includes/” has a function called “save_mod_rewrite_rules” which creates the path to the .htaccess file in a variable like this:

$home_path = get_home_path();
$htaccess_file = $home_path.'.htaccess';

The function “get_home_path” returns the base URL of the WordPress installation, and so you can see that the .htaccess file specific to WordPress is located right there. Keep in mind that you can place further .htaccess files within individual WordPress subdirectories. For example if you want to provide additional protections to certain WordPress core files to protect them from unauthorized access, all you need to do is place put a special .htaccess file into that specific folder for the rules to take effect.

Get Existing .htaccess Rules

The first step to changing .htaccess is to display the existing rules. We can do this via an existing filter called “mod_rewrite_rules”. Whenever WordPress generates a new .htaccess file and flushes its existing rules, the “mod_rewrite_rules” filter is called which allows you to change the rules or add your own ones. For example, you can paste the following into your functions.php file before the closing ?> PHP tag:

function output_htaccess( $rules ) {
echo "$rules";
return $rules;
add_filter('mod_rewrite_rules', 'output_htaccess');

This will output the .htaccess rules whenever WordPress flushes the existing ones. However, it’s important to note that this filter certainly does not run on every page load. So merely adding this to your functions.php file will not work. There are two ways to force WordPress to regenerate .htaccess. The first is to manually call “$wp_rewrite->flush_rules();” like this:

function flush_the_htaccess_file() {
    global $wp_rewrite;
add_action('admin_init', 'flush_the_htaccess_file');

This will trigger only at the admin side – which is expected since it would be too resource intensive to flush the .htaccess rules on every page load. This function will force WordPress to regenerate .htaccess and thereby trigger our “mod_rewrite_rules” filter.

The second option is to simply regenerate WordPress’s permalinks. To do this, just go to Settings-> Permalinks and click “Save Changes” without actually making any changes. If this is a one off event, the second option might be your best bet. But the first option is what you need if you want to flush the .htaccess rules programmatically.

You can see in the screenshot below what the output of my .htaccess file is like. Over here, I sent the results to the console instead of the WordPress screen:

outputing htaccess contents

You can see how to send WordPress debug messages to the console in my earlier tutorial.

This is how you see the contents of your existing WordPress .htaccess file. But what if you need to make changes? It turns out that adding your own content to .htaccess is as simple as appending a string.

Adding Your Own .htaccess Rules

Let’s say you want to add a single line to .htaccess. In the above example, we simply display the output. In order to create our own rules, simply modify it to something like this:

function output_htaccess( $rules ) {
$new_rules = <<<EOD
Add your new rules here
return $rules . $new_rules;
add_filter('mod_rewrite_rules', 'output_htaccess');

Replace the section in bold with your custom rules AS IS. In the above example, I’ve used what is known as the “heredoc” syntax for defining a string. Using this, I can use all kinds of special characters including apostrophes, double quotes, semicolons and brackets without having to bother about is giving them. It’s a great technique for when you want to store complicated HTML strings or in this case .htaccess rules.

You can see that we just store our rules into a new variable and append it to the existing set. The next time you check the output of your .htaccess file, you should see your new additional content added below. Of course, you can modify the code so that your rules are added in the beginning instead – or even perform some other kind of sophisticated string manipulation using the $rules variable.

Just keep in mind that .htaccess is an extremely sensitive file, and any error could mean the user losing all access to their website!

Adding Your Own Rewrite Rules

WordPress has a nifty function called “add_rewrite_rule()” which allows you to specify your own rewrite rules easily using regex expressions without having to manually manipulate .htaccess. So let’s say you want to access the page: by typing in .

In this example, we want to match the incoming URL, extract the number at the end of it, and construct the “real” internal URL with the page_id. Here’s what that code would look like:

function rewrite_with_posts() {
    add_rewrite_rule('^posts/([0-9]+)/?', 'index.php?page_id=$matches[1]', 'top');
add_action('init', 'rewrite_with_posts');

“add_rewrite_rule” takes three parameters. The first is the pattern to match with an incoming URL (in this case The second is the actual URL we want to request from WordPress, and we use the $matches array variable to specify that we want the number matched in the first URL to be used in the construction of the second.

Keep in mind that this rule means nothing unless WordPress actually regenerates the .htaccess file. Again, we can do this either programmatically via “$wp_rewrite->flush_rules()”, or manually by simply saving the Permalink settings in the WordPress dashboard.

These are the ways we can manipulate .htaccess files in WordPress. As you can see, everything can be done programmatically and if you’re a plugin author, this makes it easy to activate and deactivate specific rules.

Leave a Reply

This Website is Hosted by

Powered by RamNode

Disclosure: We receive a compensation from some of the companies whose products or services are presented on our website.