Ubuntu下利用Apache转发模块实现反向代理

时间:2023-12-17 20:35:14

Apache的反向代理主要利用转发模块,proxy和proxy_http

先配置 Apache 支持proxy 和 proxy_http

在Ubuntu系统下,Apache的配置文件在目录/etc/apache2下,里面会看到我们需要用到的两个目录

mods-available Apache所有的模块

mods-enabled  Apache所支持的模块

接下来需要进入mods-available 找到proxy.load和proxy_http.load 这两个模块,将这两个模块配置到mods-enabled

输入命令:

ln -s /etc/apache2/mods-available/proxy.load  /etc/apache2/mods-enabled/proxy.load

ln -s /etc/apache2/mods-available/proxy_http.load  /etc/apache2/mods-enabled/proxy_http.load

模块开通好了以后,接下来要配置一个虚拟主机,然后将虚拟主机的请求转发到指定的服务器上。

配置虚拟主机

同样也是在/etc/apache2下面有个关于虚拟主机的配置目录:

sites-available 所有可用的虚拟主机

sites-enabled  已经配置支持的主机

首先进入 sites-available 将000-default.conf拷贝并重命名为proxy.conf

编辑proxy.conf

<VirtualHost *:80>

# The ServerName directive sets the request scheme, hostname and port that

# the server uses to identify itself. This is used when creating

# redirection URLs. In the context of virtual hosts, the ServerName

# specifies what hostname must appear in the request's Host: header to

# match this virtual host. For the default virtual host (this file) this

# value is not decisive as it is used as a last resort host regardless.

# However, you must set it for any further virtual host explicitly.

ServerName example.cn  自定义的主机域名

ServerAdmin webmaster@localhost

DocumentRoot /var/www/html 指向的目录

# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,

# error, crit, alert, emerg.

# It is also possible to configure the loglevel for particular

# modules, e.g.

#LogLevel info ssl:warn

ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined

ProxyPass / http://localhost:81/  转发的主机与端口号

ProxyPassReverse / http://localhost:81/ 如果有页面的重定向,不加此项会报错,此项正是反向代理

# For most configuration files from conf-available/, which are

# enabled or disabled at a global level, it is possible to

# include a line for only one particular virtual host. For example the

# following line enables the CGI configuration for this host only

# after it has been globally disabled with "a2disconf".

#Include conf-available/serve-cgi-bin.conf

</VirtualHost>

重启Apache,即可。