0

I'm automating a server setup and to install PHP I need to add index.php to /etc/apache2/mods-enabled/dir.conf.

The target content of the file looks like this:

<IfModule mod_dir.c>

          DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm

</IfModule>

I need to add index.php before index.html.

It should end up looking like this

<IfModule mod_dir.c>

          DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm

</IfModule>

How do I do this with a shell script?

5
  • Your directive already contains an index.php, do you actually need to add it twice? Commented Sep 6, 2014 at 21:38
  • I would recommend to put all params necessary into a repository / database and generate an .htacces instead of fiddling around in central config (which needs at least a reload of apache processes once changed) Commented Sep 6, 2014 at 21:44
  • @AxelAmthor I'm simply following this tutorial to install PHP on Ubuntu 12.04 => digitalocean.com/community/tutorials/… Commented Sep 6, 2014 at 21:45
  • But that's for manual installation. I didn't get why you want to do this by a script? Commented Sep 6, 2014 at 21:48
  • Thanks for clearing that up Niels. Commented Sep 6, 2014 at 21:55

2 Answers 2

2

All you're doing is making index.php higher priority than index.html. It's an odd thing to need to do, and probably better done in .htaccess or something. However, if you really want to make the change in the config file directly you can use sed. In this case something like the following:

cd /etc/apache2/mods-enabled
sed -e 's/\s*DirectoryIndex.*$/\tDirectoryIndex index\.php <...> index\.htm/' \
    dir.conf > dir.conf.tmp && mv dir.conf.tmp dir.conf

You need to be sure that 'DirectoryIndex' only appears once though, and fill in <...> with the rest of the line (escaping dots: 'index.pl' -> 'index\.pl').

Sign up to request clarification or add additional context in comments.

Comments

1

Or you can also try the next,

  • will do the replace only inside of the <IfModule mod_dir.c> block
  • will add index.php to the begining of the line if not exists
  • reorder the line if in the index.php already exists in the line
  • don't change the other entries order
  • create an backup file .bak
conf="./dir.conf"

err() { echo "$@" >&2; return 1; }
line=$(sed '/<IfModule *mod_dir.c>/,/<\/IfModule>/!d' "$conf" | grep -o -m1 'DirectoryIndex.*')
[[ ! -z "$line" ]] || err "No mod_dir.c" || exit 1
repl=$(echo $(echo DirectoryIndex;echo index.php; tr ' ' '\n' <<<"$line" | grep -Ev 'index\.php|DirectoryIndex'))
sed -i'.bak' "/<IfModule *mod_dir.c>/,/<\/IfModule>/s/$line/$repl/" "$conf"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.