Enable ports 80 (HTTP) and 443 (HTTPS) (papercut.com)

通过iptables实现端口转发和内网共享上网 (xstarcd.github.io)

Opening a port on Linux - JournalDev

如何在 Ubuntu 18.04 上使用 UFW 管理和转发端口_allway2的博客-CSDN博客_ubuntu端口转发https://serverfault.com/questions/238563/can-i-use-ufw-to-setup-a-port-forward)


Select a Port

查看一下端口有没有被占用, 在 httpd.conf 加上 Listen 8080

netstat -na | grep :8080
ss -na | grep :8080

新版的 Ubuntu 不再使用 iptables 。所以比较麻烦。

Firewall

查看是否运行了 ufw 防火墙

systemctl status ufw

image-20220614112027913

Open Port

打开端口号:

sudo ufw allow 8080

Port Forwarding

只有 root 用户能够打开 1024 以下的端口。显然我们不希望 httpd 运行在 root 权限下

如果直接运行 httpd ,则会出现权限错误

/usr/local/apache2/bin/apachectl -D FOREGROUND

会出现如下的权限错误

(13)Permission denied: AH00072: make_sock: could not bind to address [::]:80
(13)Permission denied: AH00072: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
AH00015: Unable to open logs

修改 /etc/ufw/before.rules,在 *filter 部分之前

*nat
:PREROUTING ACCEPT [0:0]
# -A PREROUTING -p tcp --dport exposed_port -j REDIRECT --to-port effective_port
-A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
COMMIT

启用 IP forwarding, 打开 /etc/sysctl.conf

net.ipv4.ip_forward=1

保存配置

sudo sysctl -p
sudo systemctl restart ufw

Apache 2

Apache 的默认位置 /usr/local/apache2/

如果需要非 root 权限运行,要把所有相关的东西全部安装到 非 root 目录 (包括 expact, openssl, pcre, apr, apr-util)

Installing configuration files
[PRESERVING EXISTING HTDOCS SUBDIR: /usr/local/apache2/htdocs]
[PRESERVING EXISTING ERROR SUBDIR: /usr/local/apache2/error]
[PRESERVING EXISTING ICONS SUBDIR: /usr/local/apache2/icons]
[PRESERVING EXISTING CGI SUBDIR: /usr/local/apache2/cgi-bin]
Installing header files
Installing build system files
Installing man pages and online manual

需要启动 apache 2

/usr/local/apache2/bin/apachectl -D FOREGROUND

画外音

如果是不同服务器就麻烦一点

*nat
:PREROUTING ACCEPT [0:0]
# forward 202.54.1.1 port 80 to 192.168.1.100:80
# forward 202.54.1.1 port 443 to 192.168.1.100:443
-A PREROUTING -i eth0 -d 202.54.1.1   -p tcp --dport 80 -j  DNAT --to-destination 192.168.1.100:80
-A PREROUTING -i eth0 -d 202.54.1.1   -p tcp --dport 443 -j  DNAT --to-destination 192.168.1.100:443
# setup routing
-A POSTROUTING -s 192.168.1.0/24 ! -d 192.168.1.0/24 -j MASQUERADE
COMMIT