Apache 預設監聽 80 (HTTP) 和 443 (HTTPS) 埠。常見衝突場景:與 IIS/Nginx/其他服務搶埠、安全合規要求非標準埠、反向代理後端部署。本文說明修改方法、虛擬主機配置、SSL 憑證遷移與驗證。
/etc/httpd/conf/httpd.conf、/etc/httpd/conf.d/ssl.conf/etc/apache2/ports.conf、/etc/apache2/sites-available/000-default.conf、/etc/apache2/sites-available/default-ssl.confvim /etc/httpd/conf/httpd.conf
# 找到 Listen 80 → 改為
Listen 8080
# 若有 NameVirtualHost *:80 也同步改為 *:8080 (Apache 2.4 通常無此行)
vim /etc/apache2/ports.conf
# 修改
Listen 8080
# 同步修改預設站點
vim /etc/apache2/sites-available/000-default.conf
# 原 *:80
...
vim /etc/httpd/conf.d/ssl.conf
Listen 8443
# 原 _default_:443
...
SSLCertificateFile /etc/pki/tls/certs/localhost.crt
SSLCertificateKeyFile /etc/pki/tls/private/localhost.key
vim /etc/apache2/ports.conf
Listen 8443
vim /etc/apache2/sites-available/default-ssl.conf
...
SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
# 啟用 SSL 站點 (若未啟用)
a2ensite default-ssl
a2enmod ssl
systemctl restart httpd (RHEL) / systemctl restart apache2 (Debian)。若修改為非標準埠 (如 8080, 8443),SELinux 預設阻止 httpd 綁定,需執行:
semanage port -a -t http_port_t -p tcp 8080
semanage port -a -t http_port_t -p tcp 8443
# 若無 semanage:yum install -y policycoreutils-python-utils
# firewalld
firewall-cmd --permanent --add-port=8080/tcp
firewall-cmd --permanent --add-port=8443/tcp
firewall-cmd --reload
# iptables
iptables -A INPUT -p tcp --dport 8080 -j ACCEPT
iptables -A INPUT -p tcp --dport 8443 -j ACCEPT
service iptables save
# Nginx 前端監聽 443,終止 SSL,轉發至 Apache 8080 (HTTP)
# Nginx 配置片段
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.com.pem;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
location / {
proxy_pass https://127.0.0.1:8080; # Apache 後端
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https; # 關鍵:告知後端原協議為 HTTPS
}
}
# Apache 端 (8080) 只需處理 HTTP,無需配置 SSL
# 但需讀取 X-Forwarded-Proto 以生成正確重導向/安全連結
# 安裝 mod_remoteip (Apache 2.4+) 替換舊 mod_rpaf
LoadModule remoteip_module modules/mod_remoteip.so
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 127.0.0.1
ss -ltnp | grep -E ':(8080|8443)' 確認 Apache 進程監聽新埠。curl -I https://localhost:8080 / curl -Ik https://localhost:8443 (忽略自簽憑證 -k) 返回 200/301/302。/var/log/httpd/error_log 或 /var/log/apache2/error.log 無報錯。