Apache2 Web服务器常用配置
- 2026-02-26 19:28:00
- 丁国栋
- 原创 527
虚拟主机基本配置
<VirtualHost *:80>
ServerName subdomain.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/subdomain.example.com
ErrorLog ${APACHE_LOG_DIR}/error-subdomain.example.com.log
CustomLog ${APACHE_LOG_DIR}/access-subdomain.example.com.log combined
<Directory />
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
HTTP访问跳转到HTTPS访问
<VirtualHost *:80> ServerAlias example.com RewriteEngine On RewriteRule ^(.*) https://www.example.com [R=301,L] </VirtualHost>
301跳转,访问域名AAAA.com重定向到BBBB.com
<VirtualHost *:80> ServerName subdomain.AAAA.com RewriteEngine On RewriteRule ^(.*)$ https://subdomain.BBBB.com$1 [R=301,L] </VirtualHost> <VirtualHost *:443> SSLEngine On SSLCertificateFile /etc/letsencrypt/live/AAAA.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/AAAA.com/privkey.pem SSLCertificateChainFile /etc/letsencrypt/live/AAAA.com/chain.pem ServerName subdomain.AAAA.com RewriteEngine On RewriteRule ^(.*)$ https://subdomain.BBBB.com$1 [R=301,L] </VirtualHost>
反向代理
<VirtualHost *:443>
ServerName example.com
DocumentRoot /opt/example/
RewriteEngine On
RewriteCond %{HTTP:Connection} Upgrade [NC]
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /(.*) ws://127.0.0.1:8080/$1 [P,L]
<Directory />
Require all granted
</Directory>
ProxyRequests On
<proxy *>
Order deny,allow
Allow from all
</proxy>
ProxyPass / http://127.0.0.1:8080/
ProxyPassReverse / http://127.0.0.1:8080/
</VirtualHost>
---
使用 Apache2 作为 Web 服务器的一些注意事项:
- Apache 并不要求
ServerName全局唯一,这一点与 Nginx 不同,如果配置了多个相同 ServerName 的虚拟主机,使用apache2ctl -t并不会提示错误或警告,请求会交给加载顺序中第一个匹配的 vhost,后一个可能永远匹配不到,可以通过apache2ctl -S查看有哪些虚拟主机以及加载顺序等。
---
还没有评论,来做第一个吧!