Tagged: Apache Toggle Comment Threads | Keyboard Shortcuts

  • Jay Versluis 5:44 pm on October 4, 2015 Permalink | Reply
    Tags: Apache, htaccess   

    Categories: How To ( 29 )

    Apache: How to block all other IPs except for your own 

    Sometimes I have to work on WordPress sites that are too busy to display the admin interface. This can happen if there’s more traffic than the server can cope with. In such cases, we may need to tell every visitor to come back later while we carry out some maintenance.

    But how? Thanks to an Apache command to block all IP addresses, except for our own. We can even display a “maintenance” page while we’re hard at work behind the scenes.

    Let’s see how. Add the following to your .htaccess file in the web root directory, replacing with your own IP address:

    ErrorDocument 403 /maintenance.html
    Order Allow,Deny
    Allow from

    Save the file on the server and see the site speed up as of by magic. No more requests but your own shall be processed henceforth.

    Thanks to MickeyRush and b101101011011011 for this solution on Stack Overflow:

    How do I find my own IP?

    There are several services that will display the IP you’re currently connecting from. Head over to http://whatsmyip.org, or type “my ip” into Google.

    Does this work with NGINX too

    I’m sure the principle does, but I know very little about NGINX configuration. The above directive is for Apache only. If you know how this works in NGINX, please leave a comment below.

  • Jay Versluis 8:29 am on September 10, 2015 Permalink | Reply
    Tags: Apache   

    Categories: Linux ( 85 )

    How to fix a “could not bind to address” error in Apache 

    I have worked on a server recently and I came across a problem (again) that I meant to write about, and include a solution should you suffer from a similar problem. It was a Plesk server running CentOS, but this particular issue can also happen on plain LAMP stacks.

    Trying to start Apache, I got the following error message:

    apachectl -k restart
    httpd not running, trying to start
    (98)Address already in use: make_sock: could not bind to address [::]:80
    (98)Address already in use: make_sock: could not bind to address
    no listening sockets available, shutting down
    Unable to open logs

    The port number may be different depending on which port Apache is supposed to listen on (80 is the default, but depending on your system it may be something different, for example 7080). What this error is saying is that the Apache config file says the service is supposed to use a specific port, and another service is already using it. Hence, Apache can’t start or restart.

    If your server has worked fine before, then it’s likely that the config file is not the problem – so don’t go messing with it unless you absolutely know what to tweak.

    Let’s find out what service (or process) is listening on our port. We can do this using the lost command:

    lsof -i:80
    httpd   18893 apache    5u  IPv6 216716713      0t0  TCP *:http (LISTEN)
    httpd   32576 apache    5u  IPv6 216716713      0t0  TCP *:http (LISTEN)
    httpd   32576 apache  178u  IPv4 226927338      0t0  TCP us13659668780097405.dynamiccloudserver.info:33052->br218-ip02.hostgator.com.br:http (CLOSE_WAIT)
    httpd   32576 apache  180u  IPv4 236802430      0t0  TCP us13659668780097405.dynamiccloudserver.info:42497->versace.freshwebserver.com:http (CLOSE_WAIT)
    httpd   5135 apache    5u  IPv6  24375      0t0  TCP *:empowerid (LISTEN)
    httpd   5146 apache    5u  IPv6  24375      0t0  TCP *:empowerid (LISTEN)

    Replace the port number (80 in the above example) with your own. In this example, Apache is in fact listening but something isn’t quite right and it’s unable to restart. We can go and kill each of these processes using the following command:

    kill -SIGTERM 18893

    Do this with every process ID (PID) from the list you get from the lsof command. As soon as they’re all dead (verify with lsof), try to restart apache once again:

    apachectl -k restart

    This has helped me on a number of occasions ๐Ÿ˜‰

  • Jay Versluis 8:24 am on April 21, 2015 Permalink | Reply
    Tags: Apache, , NGINX   

    Categories: Plesk ( 69 )

    How to fix Apache/NGINX trouble after restarting your Plesk server 

    Plesk-LogoSome of my servers have a weird habit of throwing an Apache error after a restart: NGINX is running fine, but Apache can’t start and all websites are down. I have no idea why some servers do it and some do not. But when they do, it’s just plain annoying.

    Here are two ways to fix this problem.

    Restart Apache gracefully

    The quickest option is to shutdown NGINX, restart Apache, tell it to shutdown gracefully and then bring up NGINX again. Here are the commands that will work on CentOS 7:

    systemctl stop nginx.service
    systemctl restart httpd.service
    apachectl graceful
    systemctl restart nginx.service

    Likewise, on CentOS 6 we can use the service command to do the same:

    service nginx stop
    service httpd restart
    apachectl graceful
    service nginx restart

    Note that Apache doesn’t always like a restart – in which case, stop the service first, give it a moment and then restart it. Quirks and habits I guess.

    Thanks to Mike Yrabedra for this tip!

    If you find yourself doing this a lot, consider writing a quick script with the above commands, or restart your server less often (sometimes it’s enough to restart Plesk, or not reboot the machine at all). Alternatively, you can remove NGINX altogether and avoid such problems in the future.

    Removing NGINX from Plesk

    NGINX is not necessary – Apache will do a good job by itself. If you want to get rid of it completely, head over to Tools and Settings (or the Server Tab if you’re in Power User Mode) and select Updates and Upgrades. You’ll be taken to the Parallels Installer. Select Add/Remove Components.

    Screen Shot 2015-04-21 at 08.10.45

    Scroll down to the NGINX section under Web Hosting Features and untick both NGINX options. Now click Continue at the bottom and NGINX will be removed, leaving Apache in charge for all website connections. There’s no need to restart Plesk.


    Why would anyone want to use both NGINX and Apache together?

    Very good question indeed. Both are excellent web servers, and logic dictates that you should use one or the other. Using two web servers together is a certain sign of trouble.

    From what I understand, NGINX is not designed to be a replacement web server in Plesk (even though NGINX can be used in this way on a LAMP Stack). Instead it is implemented as an enhancement to Apache, sitting in front of it. Static files are therefore served from NGINX via Apache, and NGINX acts as a reverse proxy server.

    The benefits are faster connections and a smaller memory footprint. Read more about how NGINX and Apache are implemented in Plesk in the following articles:

  • Jay Versluis 10:06 am on February 16, 2015 Permalink | Reply
    Tags: Apache   

    Categories: WordPress ( 135 )

    How to block Spam Trackbacks in WordPress 

    wordpress-iconTrackbacks are a great way for other blogs to notify your blog about a link back to you. Many blogging platforms support this feature, including WordPress.

    But sometimes it’s very obvious that those trackbacks aren’t coming from a legitimate source, especially when you get several dozen of them every day from the same source.

    No one loves you that much.

    The most recent two examples are semalt.com and buttons-for-website.com, the latter can’t even properly mix a plural with a singular. But that’s not for here.

    To make sure those trackbacks don’t bother our WordPress site anymore, we can add a bit of code to your re-reite rule file. If your host is using Apache then this will be your .htaccess file, famously in use for Pretty Permalinks and some cache plugins.

    A typical .htaccess file is either empty or contains a block of code courtesy of WordPress. It’s a simple text file. If we add this little snippet to the bottom of the file, friendly trackbacks from semalt.com will no longer notify our website:

    # Block Semalt Trackbacks
    RewriteEngine On
    RewriteCond %{HTTP_REFERER} semalt\.com
    RewriteRule ^.* - [F,L]

    This rather strange looking code is a rewrite rule. It says “if you encounter a link or a visitor from semalt.com, then forbid them access to anywhere on this site”.

    Notice the backslash, followed by the domain extension in semalt\.com. This is necessary to escape the dot character, otherwise Apache would interpret it as an instruction. In our other example, buttons-for-website.com, we need to deal with the slashes in the domain name in the same way:

    # Block buttons-forwebsite Trackbacks
    RewriteEngine On
    RewriteCond %{HTTP_REFERER} buttons\-for\-website\.com
    RewriteRule ^.* - [F,L]

    You can stack these rules in your .htaccess file and add as many as you like for your very own Trackback Spammers. Simply replace the URL in the code with your own, escaping special characters as seen above (a special character is anything that isn’t “a to z” or “0 to 9”).

    Note that these rules do not prevent such websites from linking to you. However as soon as someone from the offending website clicks a link to your website, they will be denied access. On the other hand, when the same visitor would type in your URL, or come from a different website, they will be able so see your content without problems.

  • Jay Versluis 9:48 am on March 4, 2014 Permalink | Reply
    Tags: Apache   

    Categories: Plesk ( 69 )

    How to install Apache mod_pagespeed on CentOS with Plesk 

    Apache-LogoI bumped into Kristian Markroft from Simplyroot in New Orleans last week, and he told me about an interesting speed-up module for the Apache Webserver.

    mod_pagespeed is an open source project which speeds up page loads without having to change the code of the actual page. mod_pagespeed does this by adding filters before pages are served. For example it will resize images and minify CSS/JS files, which can speed up page load considerably. The project is hosted on Google Code:

    Let’s see how we can install it on CentOS, test to see if it works and how to manage it in Plesk.

    (More …)

    • Andy 10:56 am on April 17, 2014 Permalink | Reply

      Hi Jay, thanks for the write up.

      Do you know how well this works in Plesk 11 when you have nginx handling the static file requests? My Plesk server also runs on CentOS and I’ve been looking at installing Apache mod_pagespeed, but wasn’t sure how well this would work with Plesk’s nginx / Apache setup.

      • Jay Versluis 7:03 pm on April 17, 2014 Permalink | Reply

        Hi Andy,

        glad you liked it! I’ve had mod pagespeed running on a test server for over a month and it works really well with Plesk 11.5. All my sites are WordPress installs, where NGINX only serves static files (graphics and plain HTML, including Super Cached files). Works a treat!

        I’ve just added it to my production servers and results are great – no adverse effects at all, but several sites with complex themes show a speed improvement (including this one).

        Let me know your experience – would be nice to get another perspective.

        All the best,


        • Andy 9:37 am on May 1, 2014 Permalink | Reply

          Hi Jay,

          Thanks for taking the time to reply. I finally got round to installing this and it seems to be working well.

          I don’t know too much about what mod_pagespeed does behind the scenes, but from what I’ve read it makes optimisations to images and other resources such as CSS and JS. Like you, I’m currently using Nginx (in Plesk 11.5) to serve the static resources such as images, so I’m guessing for these file types mod_pagespeed wouldn’t have any effect as the request would never reach Apache. But if you’ve noticed a speed improvement then it must be optimising other things which is good!

          I’ll try some more speed tests and see how I get on. Thanks again,


          • Jay Versluis 4:30 pm on May 4, 2014 Permalink

            From what I understand mod_pagespeed parses all JavaScript and CSS files, and then serves each as one file rather than separate single files. So all CSS and JS is served together and is minified in the process. But the caveat is indeed that those files need to be served by Apache – so all static HTML files that rely on being served by mod_rewrite rules (for example, WP Super Cache’d files) will benefit from a speed increase – but anything served by NGINX won’t.

            I guess what would be really beneficial is a speed compare between these variations:

            • NGINX on / mod_pagespeed on
            • NGINX off / mod_pagespeed on
            • NGINX on / mod_pagespeed off

            all with and without WP Super Cache active. What’s a good website benchmark tool? Would be good to have some proper figures.

    • liamcareyLiam 2:17 pm on May 14, 2014 Permalink | Reply

      This is a great article. Am new to administering a cloud server with CentOS and Plesk. Would consider doing a short video tutorial for us newbies?

      • Jay Versluis 8:58 am on May 16, 2014 Permalink | Reply

        Sure, in fact it’s perfect timing – Plesk 12 has just been released yesterday. Is there any particular aspect you’re interested in? Administering Plesk is a complex topic and probably deserves it’s own full length course to cover all aspects.

        • Liam 12:41 pm on May 20, 2014 Permalink | Reply

          I wil be interested in backing up my websites and emails correctly and how to upgrade my Plesk panel safely. Plus any other performance tips you might have including setting up Google’s page speed service. As I’m new to this it all helps ๐Ÿ™‚

    • eomatica 6:37 pm on June 29, 2014 Permalink | Reply

      I manage a plesk 11.5 with multi php and pagespeed is only working in 5.3.27 config. Any idea how to enable it for 5.4.3 and 5.5??

      • Jay Versluis 6:51 pm on June 29, 2014 Permalink | Reply

        Pass I’m afraid – I bet it has to do with the multi PHP setup which I’ve never explored on my servers. Im not even sure how Plesk applies those.

        I’m running PHP 5.4 and mod_pagespeed works fine – but all subscriptions are running the same version of PHP.

    • donnhelela 4:52 am on January 1, 2015 Permalink | Reply

      I tried It, I have ran into an error

      Error: File contains no section headers.
      file: file:///etc/yum.repos.d/google-mod-pagespeed.repo, line: 2

      And I have tried to remove the file but failed. How can i solve this? Thanks

      • Jay Versluis 8:58 am on January 1, 2015 Permalink | Reply

        Looks like there was a problem with how you copied and pasted the text into your file. The error is rather clear and suggests your file reads ‘ogle-mod-pagespeed’ instead of ‘google-mod-pagespeed’.

        Try comparing the text visually line by line.

        • donnhelela 11:09 am on January 1, 2015 Permalink | Reply

          I did notice that, I even tried correcting it but got no where with it, it did not accept edits, I tried deleting the file and got the bellow results.

          E325: ATTENTION
          Found a swap file by the name “/etc/yum.repos.d/.google-mod-pagespeed.repo.swp”
          owned by: root dated: Thu Jan 1 12:38:35 2015
          file name: /etc/yum.repos.d/google-mod-pagespeed.repo
          modified: YES
          user name: root host name: mydomain.com
          process ID: 3678
          While opening file “/etc/yum.repos.d/google-mod-pagespeed.repo”
          dated: Thu Jan 1 08:39:36 2015

          (1) Another program may be editing the same file.
          If this is the case, be careful not to end up with two
          different instances of the same file when making changes.
          Quit, or continue with caution.

          (2) An edit session for this file crashed.
          If this is the case, use “:recover” or “vim -r /etc/yum.repos.d/google-mod-p
          to recover the changes (see “:help recovery”).
          If you did this already, delete the swap file “/etc/yum.repos.d/.google-mod-
          to avoid this message.

          Thanks for the reply ๐Ÿ˜‰

          • Jay Versluis 11:32 am on January 1, 2015 Permalink

            Remove the vi swap file like this:

            rm /etc/yum.repos.d/.google-mod-

            Then edit the file again. Using vi isn’t exactly intuitive ๐Ÿ˜‰

    • donnhelela 12:02 pm on January 1, 2015 Permalink | Reply

      I got it working mate.. thanks…. I edited the file and noticed some spaces left before the lines started. Thanks big time for the tutorial and support. ๐Ÿ˜‰

      • Jay Versluis 1:42 pm on January 1, 2015 Permalink | Reply

        Sure thing, glad your got it working. And thanks for the Facebook like ๐Ÿ˜‰

    • Tobi 5:56 am on May 21, 2015 Permalink | Reply

      Creat Tutorial !

    • mouchachnuk 5:24 am on December 16, 2015 Permalink | Reply

      Hello all,

      Do you know how to disable mod_pagespeed on a specific domain under Plesk ?

      Thanks for the reply

    • Iamkingsleyf 7:19 pm on March 23, 2016 Permalink | Reply


      Anyone for Ubuntu? also what version of PHP is supported?

  • Jay Versluis 3:01 pm on February 13, 2012 Permalink | Reply
    Tags: Apache, FastCGI, mod_fcgid   

    Categories: Plesk, WordPress ( 69 )

    FIXED: The Problem with running PHP as FastCGI Application (WordPress and Plesk) 

    We’re currently on our way to Kissimmee, FL to join Parallels Summmit, an annual conference from the people who make Plesk. We’re also taking exams in Plesk 10.4.4 so we’re studying it in-depth – I’ve been using the software for over two years now but never had formal training in it. Well here goes!

    In preparation for the exam tomorrow I’ve come across something the instructor mentioned: namely the benefits of running PHP as a FastCGI application instead of an Apache module. Sadly I’ve also come across some drawbacks when using this option in regards to WordPress. I thought I’d mention those here, alongside how to avoid those.

    UPDATE: Thanks to Boldock this problem can be fixed ๐Ÿ˜‰

    (More …)

    • Diego 11:10 pm on April 2, 2014 Permalink | Reply

      How you configure Plesk to run fastcgi ? I’m trying to use apc cache, but Parallels says that is not compatible.

      • Jay Versluis 8:04 am on April 3, 2014 Permalink | Reply

        Hi Diego,

        You can change this under Hosting Settings in the individual subscription, or in the hosting plan and then update several subscriptions at once.

        You can choose to run PHP as a classic Apache Module, FastCGI or CGI. The problem I’ve described in this article has thankfully been fixed as of Plesk 11.

    • Luka 3:20 am on July 15, 2014 Permalink | Reply

      Can u explain how to set fastcgi with Plesk? Can not find that option?
      It would be nice if someone write article how to setup MPM with plesk (who claim to not support it). Also SQL optimisation article would be great!

      • Jay Versluis 8:08 am on July 15, 2014 Permalink | Reply

        Hi Luka,

        Sure thing: you can find the FastCGI option under Service Plans – select a plan – Hosting Parameters – Scripting. There’s a dropdown menu which lets you choose how to run PHP scripts (options are Apache Module, CGI and FastCGI).

    • Frank 2:50 pm on March 27, 2015 Permalink | Reply

      I need for compatibility the direct php apache modul with the version 5.6.6 or 5.6.7.

      Every one how I can to tat?

      I can php update only for cgi / fastcgi in drop down (with Plesk), but not direkt for the apache php.

      Can you help …

      Thanks ahead Frank.

      • Jay Versluis 3:32 pm on March 27, 2015 Permalink | Reply

        Hi Frank,

        I can’t tell you how, but I can tell you why: when Plesk runs PHP as CGI or FastCGI module, it is executed as the subscription’s system user and not as Apache. Therefore, when you add multiple versions of PHP to Plesk that way, the actual Apache daemon is not affected by that change. The system wide Apache version number depends on the distribution’s vendor packages.

        The only two distributions I know of that support PHP 5.6.6 / 5.6.7 right now are Fedora (rawhide) and Debian (Jessie). Both are in beta stages at the time of writing. If you desperately need PHP 5.6 for the overall Apache daemon on your Plesk system, your only option is to completely remove it from the system and compile it from source (good luck with that).

    • Frank 4:14 pm on March 27, 2015 Permalink | Reply

      Hi Jay,

      Im hopefull to compile in plesk same like cgi & fast cgi php (drop down menu) in Plesk…
      Only with Apache2 php with drop down menu to switch version.

      The problem is, my programmer written a very big PHP, the script load arround 7.000 articels to my shopsystem, and this works only with Apache2 PHP, not with CGI or fastCGI, CGI and fastcgi brocken the transfer after 12min….

      Thanks for you’re information…

      Thanks for luck ;)…
      Greadings Frank.

    • Frank 5:41 pm on March 28, 2015 Permalink | Reply


      I compiled again and again, and now works with CGI :)…

      … I hope it will work if I recompile again :).

      I can say now, It works better, als only with Apache2!

      Maybe it’s the engine.

      Nice Weekend and Greedings Frank.

    • jasonjudge 8:41 am on July 19, 2015 Permalink | Reply

      So the PHP files are all owned by the same web user that runs them? That is very convenient. But what a security nightmare – one tiny chink in the armour of one script, and you have a rampant hacker putting backdoors into every, single, PHP script on that site. There is a reason why you need to mess around with file and directory permissions to get a site running. That reason is security.

      • Jay Versluis 8:52 am on July 19, 2015 Permalink | Reply

        Your comment is a bit off-topic here, but isn’t that the point of running PHP as CGI module or using suPHP? So that every website is run as a separate user? Otherwise ALL websites would be run by Apache, and THAT is the security nightmare you’re talking about.

  • Jay Versluis 1:11 pm on January 11, 2012 Permalink | Reply
    Tags: Apache, , Mod Rewrite   

    Categories: Linux ( 85 )

    How to prevent direct file access in your wp-content directory 

    I was working on a secure site with sensitive video material that we needed strict members access to. Even though many plugins can make sure your direct permalinks can only be seen by logged in members, direct links to files in your wp-content directory are still accessible to others. They can even be hotlinked from other sites.

    One way around this is to move the wp-content directory outside the web visible portion of your directory on the server, but even so WordPress can always link to such files. A better way is to tell your server not to give access to certain files (say ending with mp4 or mp3) and only allow access from your own domain.

    We can use Apache Mod Rewrite for this – it’s a complex language that you can utilise in your .htaccess file within the wp-content folder.

    Let me show you how to keep prying eyes out of your content.

    (More …)

    • Shannon 9:13 pm on January 17, 2013 Permalink | Reply

      If adding to an existing .htaccess file, should this be added prior to or after the existing file contents? Or does it not matter?

      • Jay Versluis 9:25 pm on January 17, 2013 Permalink | Reply

        Technically it doesn’t matter, I think I would put this code first before anything else gets executed.

    • Makarand Mane 2:39 pm on March 3, 2013 Permalink | Reply

      i have uploded this code

      RewriteEngine On
      RewriteCond %{HTTP_REFERER} !^http://(www\.)?eduvarsha.\.com/ [NC]
      RewriteCond %{REQUEST_URI} !hotlink\.(doc|xls|pdf|html|htm|xlsx|docx|mp4|mov) [NC]
      RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
      RewriteRule .*\.(doc|xls|pdf|html|htm|xlsx|docx|mp4|mov)$ http://eduvarsha..com/ [NC]

      but not working properly at the time of redirect

      • Jay Versluis 11:18 pm on March 3, 2013 Permalink | Reply

        Looks like you’re redirecting to eduvarsha..com

        • Makarand Mane 8:31 am on March 22, 2013 Permalink | Reply

          Finally below code worked properly for my site:

          Options +FollowSymlinks
          RewriteEngine On
          RewriteCond %{HTTP_REFERER} !^$
          RewriteCond %{HTTP_REFERER} !^http://(www\.)?eduvarsha.\.com/ [NC]
          RewriteCond %{REQUEST_URI} !hotlink\.(pdf|doc|docx|xlsx|xls|ppt|pptx|zip) [NC]
          RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
          RewriteRule .*\.(pdf|doc|docx|xlsx|xls|ppt|pptx|zip)$ http://www.eduvarsha.com/wp-login.php?redirect_to=%{REQUEST_URI} [NC]

        • Makarand Mane 8:36 am on March 22, 2013 Permalink | Reply

          I am using hosting @mediatemple.net

    • matteo 12:11 am on April 13, 2013 Permalink | Reply

      GREAT. Very useful for our forthcoming private music community.

    • Kevin ONeill 5:38 pm on April 24, 2013 Permalink | Reply

      Using the following in .htaccess palced in “uploads”:

      IndexIgnore *
      Options +FollowSymlinks
      RewriteEngine On
      RewriteCond %{HTTP_REFERER} !^https://(www\.)? flyfrompti\.com/ [NC]
      RewriteCond %{REQUEST_URI} !hotlink\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov|txt) [NC]
      RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
      RewriteRule .*\.(gif|png|jpg|doc|xls|pdf|html|htm|xlsx|docx|mp4|mov)$ https://www.flyfrompti.com/access-denied/ [NC]

      However, direct access is still available. Anyideas?


      • Jay Versluis 6:50 pm on April 24, 2013 Permalink | Reply

        Looks good to me. I’m not familiar with the first two lines though so I’d take those out. Did you clear your browser cache before trying it again? And are you sure you’re logged out? I like testing this with two different browsers, one where I’m logged in and one where I’m not. Also, since you’re using https, check that the file which still gets through is using https too. Perhaps the browser is clever and redirects the file via http, hence Apache will let it pass.

        Once you’ve checked your browsers, check with your host if you’re allowed to override your Apache configuration via .htaccess files – some hosts won’t allow this for security reasons.

    • Braus 1:33 am on May 30, 2013 Permalink | Reply

      This .htaccess is a good way to use COOKIES to prevent direct access, but not enough. If you login into another wordpress site or copy the cookie to you computer you will be able to pass through this security script.
      Have a look into this http://wordpress.stackexchange.com/questions/37144/how-to-protect-uploads-if-user-is-not-logged-in

    • Stephen Howell 8:25 am on July 20, 2013 Permalink | Reply

      Do you think this approach would stop comment spammers from accessing WP core files wp-trackback.php and wp-comments-post.php?

      By putting .htaccess in the /wordpress sub-directory …

      RewriteEngine On
      RewriteCond %{HTTP_REFERER} !^http://(www\.)?yoursite\.com/ [NC]
      RewriteCond %{REQUEST_URI} !hotlink\.(wp-trackback.php|wp-comments-post.php) [NC]
      RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
      RewriteRule .*\.(php)$ http://yoursite.com/ [NC]


      • Jay Versluis 8:31 am on July 20, 2013 Permalink | Reply

        Hi Stephen,

        That’s an interesting idea, I guess it would stop anyone from writing a comment who’s not logged into to the site, spammer or not.

        • Stephen Howell 8:56 am on July 20, 2013 Permalink | Reply

          I’ve been hunting for a way to stop comment spammers who are posting comments to WP sites directly bypassing WP login and comment controls. I’m not in favor of modifying core files because then you create a separate maintenance path and upgrades become difficult or impossible.

          I’m not sure how to test this strategy out. Any thoughts?

          • Jay Versluis 9:06 am on July 20, 2013 Permalink

            I’d say try it out and see if it’s effective. Try to post as a non-logged in user too and see what happens (you’re most likely being redirected when you try to post, so not an ideal user experience).

            The only option to cut down on comment spam is lock down comments by switching on the option to only let logged in users comment (under Settings – Discussion). In which case, you wont need to prevent access to the core files.

            Alternatively you can switch off comments altogether and provide a different alternative for users to participate in a discussion.

          • Stephen Howell 9:15 am on July 20, 2013 Permalink

            Believe me I have all those options implemented and they’re still posting comments. They’re are able to bypass all WP core logic that checks for valid subscribers who are logged in. They’re posting comments on posts even after comments are closed. They’re ruthless, so, I’m looking for ways to harden the system to ensure that comments must be open (meaning ok to post comments) and that the user must be logged in, etc.

            This has been a difficult problem to solve. Most solutions suggest deleting either or both wp-trackback.php and wp-comments-post.php. But that disables comments all together.

            Other solutions suggest modifying some of the code in wp-comments-post.php by removing a couple of lines of code in the default case structure. Again modifying core files creates maintenance problems.

          • Jay Versluis 9:49 am on July 20, 2013 Permalink

            Sounds like you’ve got your hands full. There’s an option for “anyone to register” under Settings – General, is that option ticked? Because if it is. It’s feasible for hackers to simply register and then comment. I’ve had good results unchecking that option to cut down on the amount of rogue users on some installations that had this switched on.

            Which anti-spam solution are your using? Perhaps it’s worth to switch to another.

            I can think of one other option to allow comments yet keep spammers out: create a “members section” in. Which registered users have access to the comment feature. WP eMember is one I’ve used in the past. It can integrate with your current users but maintains its own database of access rights. This approach isn’t right for every website and adds an extra layer of complexity, but its another option.

      • Stephen Howell 8:39 am on July 21, 2013 Permalink | Reply

        Any rewrite is bounded to root, so a small correction to the code above is posted below …

        RewriteEngine On
        RewriteCond %{HTTP_REFERER} !^http://(www\.)?yoursite\.com/ [NC]
        RewriteCond %{REQUEST_URI} !hotlink\.(wp-trackback.php|wp-comments-post.php) [NC]
        RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
        RewriteRule .*\.(wp-trackback.php|wp-comments-post.php)$ http://yoursite.com/ [NC]

    • Stephen Howell 9:59 am on July 20, 2013 Permalink | Reply

      This issue I’m having isn’t registered users spamming the site, it’s comment spammers bypassing all restrictions and deselected options. The comments are getting trapped and pending approval before posting, so they’re not slipping by unnoticed. So core WP code and plug-ins are working and trapping everything except for a few very sneaky comment spammers. If this works, then this is a very simple fix that is easy to implement without much fuss and blocks one more access point!

      • Jay Versluis 10:07 am on July 20, 2013 Permalink | Reply

        Let me know if it works, I’d be interested to know.

        I must admit I’m (luckily) not in that situation. According to my Akismet stats, I’m getting roughly 10.000 spam comments every month in this site, but only a handful slip through (between 5 and 10) so it’s doing a good job. Which makes me curious as to what is causing spammers to get through on your site.

        • Stephen Howell 7:07 am on July 21, 2013 Permalink | Reply

          It’s not what is causing spam to get through, more about how it’s getting through to a WP site. I’ve narrowed it down to a hack targeting WP core files that could make it possible to programmatically post comments without going through the comment dialog of the blog and spam blocker plug-ins installed to reduce spam.

          In the wp-comments-post.php source you’ll find:

          if ( !comments_open($comment_post_ID) ) {
          do_action(‘comment_closed’, $comment_post_ID);
          wp_die( __(‘Sorry, comments are closed for this item.’) );
          } elseif ( ‘trash’ == $status ) {
          do_action(‘comment_on_trash’, $comment_post_ID);
          } elseif ( !$status_obj->public && !$status_obj->private ) {
          do_action(‘comment_on_draft’, $comment_post_ID);
          } elseif ( post_password_required($comment_post_ID) ) {
          do_action(‘comment_on_password_protected’, $comment_post_ID);
          } else {
          // * * * * * * * * * * * * * * * * * * * * * * * * *************
          // * * * * * * * * * * * * * * * * * * * * * * * * *************
          do_action(‘pre_comment_on_post’, $comment_post_ID);

          I’m not wanting to comment this line out as other sources have suggested. Because it creates a maintenance vector that I don’t want to have to manage. Hence my search for hardened approach to blocking spambot posters. As you suggested, the volume of errant spam posts that sneak through are very very few. Only the ruthless seem to be able to bypass plugins designed to defeat them. But, I’m annoyed with even those few posts that go unblocked. I want open sites for visitor engagement and at the same time I want to eliminate all the spam.

    • Maria 11:33 pm on May 21, 2015 Permalink | Reply

      Hey! Thanks for this code.

      I’m trying to use it on a WP site — it doesn’t allow hotlinking, but it still allows direct access — if I put in the URL in a browser window it comes up with the file. Any idea what could be going on?

      • Jay Versluis 4:15 pm on May 30, 2015 Permalink | Reply

        Hi Maria, my guess is that you’re trying it with the website in question loaded already. We’re telling Apache “if a visitor from another website wants the file, redirect him”. Try building a link to your file from another website and click that link. It shouldn’t work.

        Typing the link directly into the browser however will work – otherwise the file would be unaccessible for everybody.

    • Robert 1:45 pm on September 25, 2015 Permalink | Reply

      Thank you very much for the code it work perfectly on our site, we added the code at the end of the existing httaccess in the MAIN WP folder and all direct access was blocked and redirected to our home page.

      Thank you again.

      • Jay Versluis 1:02 pm on September 26, 2015 Permalink | Reply

        Great to hear it, Robert!

compose new post
next post/next comment
previous post/previous comment
show/hide comments
go to top
go to login
show/hide help
shift + esc