Posts Tagged ‘apache’

Using sed to search and replace contents of next line in a file.

January 24th, 2012 2 comments

This example will show you how easy it is using sed to find a particular line in a file and replace all or part of the next line. In this example, using htaccess we want to deny access to all clients except a particular dynamic IP (for your home connection for instance).

Your .htaccess file might look like this:

order deny,allow
deny from all

# allow from
allow from

And your sed code to update the allowed IP address might look like this:

sed -i -r "/# allow from{\
n; s/([0-9]{1,3}.){3}[0-9]{1,3}/\
}" .htaccess

Let’s look at it piece by piece.

  • /# allow from will search the file for this string. The I flag at the end makes the search case insensitive.
  • n; will tell sed to continue processing on the next line.
  • s/([0-9]{1,3}\.){3}[0-9]{1,3}/ will regex search for an IP and replace the match with your updated IP (in this case
  • .htaccess is of course the input file to process.

Note that in .htaccess files, comments must be on a line of their own. End of line or inline comments are not permitted. In cases where you do not need to replace a part of the next line but rather all of it, our replacement becomes s/.*/

Categories: All, Linux

Apache virtual hosts, _default_ and ServerName

December 2nd, 2009 3 comments

I’ve recently changed my VPS provider. I won’t go into why, that’s a separate post for when I find the time and nerves to write about it.

Given the opportunity of the move, I decided to split my VirtualHost configuration out of a single httpd.conf file into per virtual-host config files. This by chance, is something that I knew that I could do since 1696 but never really realized the advantages of doing so before now.

Anyway, the mistake I made was to assign ServerName in httpd.conf to either a named or aliased VirtualHost. This caused a conflict which was solved as soon as I changed ServerName to something totally irrelevant.

Categories: All, Linux