Add lines to .htaccess file via plugin or theme

I have been reading up on analytics spam and have been looking for a way of dealing with it across multiple wordpress sites I run. The best solution seems to be to block the hostname via my htaccess file. The issue is I would need to set this up manually across all sites, making initial setup time-consuming and ongoing maintenance a nightmare!

My question is this: can I include this information within a plugin or theme file - i.e. create a plugin that alters the htaccess file to filter out from a master list of hostnames?

I am aware there are a few plugins out there that offer htacces edits, but I would like to create my own as I'll only be using it on a very select set of sites.

  • Adam Czajczyk

    Hey ks-webdesigner,

    I hope you're well today and thank you for your question!

    This should be doable. I suppose you're familiar with writing plugins, am I correct?

    I think you should create a list of .htaccess rules that would be stored in a simple text file (just like .htaccess itself) and these would be only those "security rules" to be added to the original .htaccess. You would store this file on a server under the publicly accessible URL.

    Your plugin should then upon first activation make a "reference" copy of an original .htaccess of the site it's been installed. This is necessary because there might be some differences in .htaccess files from site to site (it may be altered by another plugin for example).

    Then it could periodically access this given URL and fetch your "security" file with cURL. Once this is fetched plugin then would read the "reference" file, merge both files and write it as a .htaccess file.

    The only drawback here is the possibility of a .htaccess file being modified by another plugin after it has already been initially modified by your plugin. Then, such an action would flush these changes.

    The solution would most likely be for your plugin to keep "last modified" date of .htaccess file in the database and check it upon each "sync": if stored date is older than the actual file modification date it would mean that the .htaccess was modified manually or by other plugin, therefore it would be then used instead of "reference" one.

    I hope that makes sense :slight_smile:

    I realize this is just a general answer but if you have any specific question or require some further assistance, I'll be glad to help!

    Cheers,
    Adam

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.