配置 Apache 反向代理到后端其它软件(ngrok、ASP.NET 等)

发布于 2016-04-28  770 次阅读


同一个服务器需要部署多个软件,但是 80 端口只能给一个,这时候我们需要使用反向代理。Nginx 的反向代理相对简单,Apache 也仅需简单配置即可。

这里特别介绍 RewriteRule 配置中的 [P] 标记,这是 2.4 版的新特性,所以在网络上很多的老旧资料中是找不着的。官方 Wiki 介绍(英文):http://httpd.apache.org/docs/2.4/rewrite/flags.html#flag_p

以本服务器为例,下面是 ngrok 的配置文件:

<VirtualHost *:80>
ServerName main.ngrok.skitisu.com
ServerAlias *.ngrok.skitisu.com
RewriteEngine On
RewriteRule ^/(.*) http://%{HTTP_HOST}:8000/$1 [P]
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass / http://localhost:8000/
ProxyPassReverse / http://localhost:8000/
</VirtualHost>

对于 ASP.NET WEB API 程序,我需要将/跳转到 index.html 但保持网址不变,配置如下:

<VirtualHost *:80>
ServerName numgame.skitisu.com
RewriteEngine On
# 判断语句,如果请求的参数为/
RewriteCond %{REQUEST_URI} =/
# 那么反代到后端软件的/index.html
RewriteRule / http://localhost:5000/index.html [P]
# 否则正常传递请求参数反代
RewriteRule ^/(.*) http://localhost:5000/$1 [P]
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass / http://localhost:5000/
ProxyPassReverse / http://localhost:5000/
</VirtualHost>

寻找属于自己的1%