如何使用Shell脚本使'index.php'优先于'index.html'

时间:2014-09-06 21:35:22

标签: php shell unix

我正在自动化服务器设置并安装PHP我需要将index.php添加到/etc/apache2/mods-enabled/dir.conf

文件的目标内容如下所示:

<IfModule mod_dir.c>

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

</IfModule>

我需要在index.php之前添加index.html

它应该看起来像这样

<IfModule mod_dir.c>

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

</IfModule>

如何使用shell脚本执行此操作?

2 个答案:

答案 0 :(得分:2)

您所做的只是使index.php的优先级高于index.html。这是一个奇怪的事情需要做,而且可能在.htaccess或其他什么方面做得更好。但是,如果您确实想直接在配置文件中进行更改,可以使用sed。在这种情况下,如下所示:

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

您需要确保&#39; DirectoryIndex&#39;只出现一次,并填写&lt; ...&gt;与剩余的一行(逃避点:&#39; index.pl&#39; - &gt;&#39; index \ .pl&#39;)。

答案 1 :(得分:1)

或者您也可以尝试下一个,

  • 只会在<IfModule mod_dir.c>
  • 内进行替换 如果不存在,
  • 会将index.php添加到该行的开头
  • 如果行中已存在index.php
  • ,则重新排序该行
  • 不要更改其他条目订单
  • 创建备份文件.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"