I'm setting up an Amazon Web Service Stack and I'd like to configure the Document Root in /etc/apache2/sites-enabled/000-default.conf which I currently do by modifying the document's DocumentRoot. I then reflect this change in /etc/apache2/apache2.conf. Is it possible to make these changes with command lines as opposed to opening and editing files? Thanks in advance.
-
Yes you have to use a command line editor to edit the file like "nano" – Piyush Patil Jul 25 '16 at 22:25
-
Use vim instead. – quant Dec 28 '18 at 08:22
3 Answers
You can do it with sed. I use following wrapper function, to make it more convenient:
replace_string () {
while :; do
case $1 in
file=?*) local file=${1#*=} ;;
replace=?*) local replace=${1#*=} ;;
with=?*) local with=${1#*=} ;;
*) break ;;
esac
shift
done
sudo sed -i -- "s/$replace/$with/ig" $file
}
replace_string file='/etc/apache2/sites-enabled/000-default.conf' \
replace='.*DocumentRoot.*' \
with='DocumentRoot path-to-your-document-root'
replace_string file='/etc/apache2/apache2.conf' \
replace='.*DocumentRoot.*' \
with='DocumentRoot "path-to-your-document-root"'
Mind that user running this script should be capable of using sudo without a password.

- 686
- 5
- 9
-
-
@quant I hate bash and love ruby, so I've got a whole "framework" of such functions. – olmstad Dec 25 '18 at 08:42
If you have httpd.conf file
I don't know if this is supported by the documentation or not (I couldn't see reference to it) but I found that appending will replace previous directives.
I stumbled upon this experimentally after becoming disillusioned with the cocophony of sed
, grep
and awk
scripts that usually accompany this kind of question (see Modify config file using bash script).
In my case, I have a file called httpd_changes.conf
which looks like this:
DocumentRoot "/my/new/web/dir"
<Directory "/my/new/web/dir">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
Then when I set up the webserver (in my case it's in my Dockerfile
) I run this prior to starting the httpd
service:
cat httpd_changes.conf >> /etc/apache2/httpd.conf
If you don't have a httpd.conf file
This isn't my situation but as far as I can tell you can just put a new config file in your conf.d
directory. Those files are read in alphabetically (according to this page https://superuser.com/questions/705297/in-what-order-does-apache-load-conf-files-and-which-ones) which is obviously much nicer than my hack.

- 21,507
- 32
- 115
- 211
You could try the following:
sed "s,/var/www/html,/my/new/web/dir,g" /etc/apache2/sites-enabled/000-default.conf
This will display the modification that would be made on your file.
The ,
is used as a custom delimiter to make the regex easier to read.
This example with replace all occurences of /var/www/html
with /my/new/web/dir
.
Add the -i
flag to actually modify the file:
sed -i "s,/var/www/html,/my/new/web/dir,g" /etc/apache2/sites-enabled/000-default.conf

- 1,900
- 4
- 21
- 32