Use .htaccess to Prevent WP-Admin Access on Local and Staging

More than once, I’ve accidentally edited a post on my local WordPress site thinking that I was on the live site, then synched the databases and lost my work. It sucks. A lot. Luckily, there’s an easy solution…

With a few easy lines in your site’s .htaccess file, you can prevent access to your local WP-Admin folder (staging too, or local Drupal admin, etc. — the same basic idea can be edited for lots of purposes.

Here’s an example using https://example.com as the site URL and wp-admin as the admin path:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_NAME} !^example\.com$
RewriteRule ^wp-admin* https://example.com%{REQUEST_URI} [R=301,L]
</IfModule>

The RewriteCond line says that the rule we’re about to create applies to any traffic not on example.com (note the exclamation mark — if you remove it, the rule applies only to example.com).

And then the RewriteRule line actually creates the rule. We’re telling the server to move any traffic that starts with wp-admin over to the same path on https://example.com.

So, for example, if you tried to access:

http://example/wp-admin/post.php?post=132&action=edit

You’d end up here instead:

https://example.com/wp-admin/post.php?post=132&action=edit

To change this to apply to Drupal’s admin section, simply change ^wp-admin* to ^admin* — the ^ indicates that you’re at the start of the path, and the * is a wildcard meaning that anything (or nothing) can follow and still get caught by the rule.

Or to change this to lockdown your live site’s WP-Admin section while you’re making big changes on local, you’d swap out !^example\.com$ for !^example$ on the RewriteCond line.


Comments

Loading…

This post was published on July 26th, 2018 by Robert James Reese. Before using any of the code or other content in this post, you must read and agree to our terms of use.