关于 apache 服务器的使用学习

看人家的教程都是在 windows 环境下配置的 apache,我在这里用 linuxmint 研究了一下 apache2,顺手写一下笔记
安装方法:

1
sudo apt-get install apache2

其实我是冲着搭建 LAMP 环境来的,mysql 和 php 暂时就不说了
查了一下 apache2 安装完之后的目录结构
默认主要安装到了一下目录

1
2
/etc/apache2/
/usr/share/apache2/

主配置文件 apache2.conf 在 /etc/apache2 下
默认主页 index.html 在 /usr/share/apache2/default-site 下
这个是官方给的一个目录结构

1
2
3
4
5
6
7
8
9
10
/etc/apache2/
|-- apache2.conf
| `-- ports.conf
|-- mods-enabled
| |-- *.load
| `-- *.conf
|-- conf-enabled
| `-- *.conf
|-- sites-enabled
| `-- *.conf

默认主站位置在这里 The default Ubuntu document root is /var/www/html
了解到这里差不多先够了,下面来一步一步记录一下 apache2 的使用方法

一、启动,关闭,重启 apache2,有两种方法

第一种是直接用 apachectl

1
2
$ apachectl
Usage: /usr/sbin/apachectl start|stop|restart|graceful|graceful-stop|configtest|status|fullstatus|help

第二种是直接的简单启动方式

1
/etc/apache2 {start|stop|graceful-stop|restart|reload|force-reload|start-htcacheclean|stop-htcacheclean}

当第一种启动方式启动不了的时候,就尝试使用第二种启动方式,在端口和进程都正常的情况下,第二种启动方式绝对可以达到目的。

二、配置 apache2 的服务端口

比如配置 HTTP 访问端口到 8080

1
sudo vi /etc/apache2/ports.conf

我们会看到这一行

1
LISTEN 80

只需把上面的 80 改成 8080,然后重启 apache2 即可

三、编辑默认主站位置

也就是找到 DocumentRoot 的位置,这个不像 windows 里的 apache 那样全都放在了 httpd.conf 里,而是放在了 / etc/apache2/sites-enabled / 的那个 conf 文件里
在这个文件夹里,我只看到了一个 conf 文件,所以很容易就找到了

1
2
3
4
5
/etc/apache2/sites-enabled $ ls -al
total 8
drwxr-xr-x 2 root root 4096 Mar 18 17:31 .
drwxr-xr-x 8 root root 4096 Mar 18 17:35 ..
lrwxrwxrwx 1 root root 35 Mar 15 21:11 000-default.conf -> ../sites-available/000-default.conf

它是 link 到 sites-available 的一个文件, 既然只有一个,那就方便了
直接 $ vi 000-default.conf,结果很快就看到了

1
DocumentRoot /var/www/html

修改之后重启 apache 即可
其实 ServerName 也可以在这里改,在这里就不细说了。

四、修改默认加载页面

也就是原来 windows 下的 httpd.conf 里的 IfModule dir_module
在 linux 下它被放在了 / etc/apache2/mods-enabled/dir.conf 里
要修改直接 vi 即可

1
2
<ifmodule mod_dir.c="">
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm

修改完后记得重启 apache

五、修改访问权限

这个要到 conf-enabled 目录里去设置,应该是 security.conf 这个文件

1
vi conf-enabled/security.conf

然后在末尾添加相应的访问权限语句即可,修改完后重启 apache 即生效

六、虚拟主机配置

这个其实也是在 000-default.conf 里面配置
之前在看 ports.conf 的时候,已经看到了这样的提示

1
2
3
# If you just change the port or add more ports here, you will likely also
# have to change the VirtualHost statement in
# /etc/apache2/sites-enabled/000-default.conf

所以其实前面改端口的时候,也需要同时过去重新配置好虚拟主机的端口

1
vi sites-enabled/000-default.conf

只需根据里面的注释来配置即可,配置完后要重启 apache