Apache Web Server Kurulumu ve Yönetimi

Apache HTTP Server kurulumu, virtual host yapılandırması, SSL sertifikası, mod_rewrite ve performans optimizasyonu. Web sunucu yönetimi rehberi.

8 min read
1.451 words

Apache Web Server Kurulumu ve Yönetimi#

Apache HTTP Server, dünya çapında en yaygın kullanılan web sunucularından biridir. Bu rehberde Apache kurulumu, yapılandırması ve yönetimi konularını detaylı olarak ele alacağız.

Apache Kurulumu#

Ubuntu/Debian Sistemlerde Kurulum#

# Paket listesini güncelle sudo apt update # Apache2 kurulumu sudo apt install apache2 # Apache servisini başlat ve etkinleştir sudo systemctl start apache2 sudo systemctl enable apache2 # Apache durumunu kontrol et sudo systemctl status apache2 # Firewall ayarları sudo ufw allow 'Apache Full'

CentOS/RHEL Sistemlerde Kurulum#

# Apache (httpd) kurulumu sudo yum install httpd # Servisi başlat ve etkinleştir sudo systemctl start httpd sudo systemctl enable httpd # Firewall ayarları sudo firewall-cmd --permanent --add-service=http sudo firewall-cmd --permanent --add-service=https sudo firewall-cmd --reload

Temel Apache Yapılandırması#

Ana Yapılandırma Dosyası#

Ubuntu/Debian: /etc/apache2/apache2.conf CentOS/RHEL: /etc/httpd/conf/httpd.conf

# Temel sunucu ayarları ServerRoot "/etc/apache2" PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 # MPM (Multi-Processing Module) ayarları <IfModule mpm_prefork_module> StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxRequestWorkers 256 MaxConnectionsPerChild 0 </IfModule> # Güvenlik ayarları ServerTokens Prod ServerSignature Off # Dizin ayarları <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> # Log ayarları ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common

Modül Yönetimi#

# Mevcut modülleri listele apache2ctl -M # Modül etkinleştir sudo a2enmod rewrite sudo a2enmod ssl sudo a2enmod headers # Modül devre dışı bırak sudo a2dismod autoindex # Apache'yi yeniden yükle sudo systemctl reload apache2

Virtual Host Yapılandırması#

Temel Virtual Host#

# /etc/apache2/sites-available/example.com.conf <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html # Log dosyaları ErrorLog ${APACHE_LOG_DIR}/example.com_error.log CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined # Dizin ayarları <Directory /var/www/example.com/public_html> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost>

SSL Virtual Host#

# /etc/apache2/sites-available/example.com-ssl.conf <VirtualHost *:443> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html # SSL ayarları SSLEngine on SSLCertificateFile /etc/ssl/certs/example.com.crt SSLCertificateKeyFile /etc/ssl/private/example.com.key SSLCertificateChainFile /etc/ssl/certs/example.com-chain.crt # SSL güvenlik ayarları SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384 SSLHonorCipherOrder on # HSTS header Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" # Log dosyaları ErrorLog ${APACHE_LOG_DIR}/example.com_ssl_error.log CustomLog ${APACHE_LOG_DIR}/example.com_ssl_access.log combined <Directory /var/www/example.com/public_html> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost> # HTTP'den HTTPS'e yönlendirme <VirtualHost *:80> ServerName example.com ServerAlias www.example.com Redirect permanent / https://example.com/ </VirtualHost>

Site Etkinleştirme#

# Site yapılandırmasını etkinleştir sudo a2ensite example.com.conf sudo a2ensite example.com-ssl.conf # Yapılandırmayı test et sudo apache2ctl configtest # Apache'yi yeniden yükle sudo systemctl reload apache2

SSL Sertifikası Kurulumu#

Let's Encrypt ile Ücretsiz SSL#

# Certbot kurulumu sudo apt install certbot python3-certbot-apache # SSL sertifikası al sudo certbot --apache -d example.com -d www.example.com # Otomatik yenileme testi sudo certbot renew --dry-run # Cron job ekle echo "0 12 * * * /usr/bin/certbot renew --quiet" | sudo crontab -

Manuel SSL Sertifikası Kurulumu#

# Özel anahtar oluştur sudo openssl genrsa -out /etc/ssl/private/example.com.key 2048 # CSR (Certificate Signing Request) oluştur sudo openssl req -new -key /etc/ssl/private/example.com.key -out /tmp/example.com.csr # Self-signed sertifika oluştur (test için) sudo openssl x509 -req -days 365 -in /tmp/example.com.csr -signkey /etc/ssl/private/example.com.key -out /etc/ssl/certs/example.com.crt

.htaccess ve mod_rewrite#

Temel .htaccess Kullanımı#

# /var/www/example.com/public_html/.htaccess # Rewrite engine etkinleştir RewriteEngine On # HTTPS'e yönlendirme RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # www olmayan versiyona yönlendirme RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ https://%1/$1 [R=301,L] # Clean URL'ler RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+)/?$ page.php?slug=$1 [L,QSA] # Dosya uzantısını gizle RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L] # Cache control <IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 month" ExpiresByType image/jpeg "access plus 1 month" ExpiresByType image/gif "access plus 1 month" ExpiresByType image/png "access plus 1 month" ExpiresByType text/css "access plus 1 month" ExpiresByType application/pdf "access plus 1 month" ExpiresByType text/javascript "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" </IfModule> # Gzip sıkıştırma <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript </IfModule> # Güvenlik headers <IfModule mod_headers.c> Header always set X-Frame-Options "SAMEORIGIN" Header always set X-XSS-Protection "1; mode=block" Header always set X-Content-Type-Options "nosniff" Header always set Referrer-Policy "strict-origin-when-cross-origin" </IfModule> # Dosya erişimini engelle <Files ~ "^\."> Order allow,deny Deny from all </Files> # Belirli dosya türlerini engelle <FilesMatch "\.(htaccess|htpasswd|ini|log|sh|inc|bak)$"> Order Allow,Deny Deny from all </FilesMatch>

PHP Yapılandırması#

PHP-FPM ile Apache Entegrasyonu#

# PHP-FPM kurulumu sudo apt install php-fpm # Apache PHP-FPM modülünü etkinleştir sudo a2enmod proxy_fcgi setenvif sudo a2enconf php7.4-fpm # Apache'yi yeniden başlat sudo systemctl restart apache2

Virtual Host'ta PHP Yapılandırması#

<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/example.com/public_html # PHP-FPM yapılandırması <FilesMatch \.php$> SetHandler "proxy:unix:/var/run/php/php7.4-fpm.sock|fcgi://localhost" </FilesMatch> # PHP dosyalarını doğrudan erişimden koru <Files ~ "\.php$"> Require all granted </Files> <Directory /var/www/example.com/public_html> Options -Indexes +FollowSymLinks AllowOverride All Require all granted DirectoryIndex index.php index.html </Directory> </VirtualHost>

Performans Optimizasyonu#

MPM (Multi-Processing Module) Ayarları#

# Prefork MPM (PHP mod_php için) <IfModule mpm_prefork_module> StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxRequestWorkers 256 MaxConnectionsPerChild 4000 </IfModule> # Worker MPM (daha iyi performans) <IfModule mpm_worker_module> StartServers 3 MinSpareThreads 75 MaxSpareThreads 250 ThreadsPerChild 25 MaxRequestWorkers 400 MaxConnectionsPerChild 0 </IfModule> # Event MPM (en iyi performans) <IfModule mpm_event_module> StartServers 3 MinSpareThreads 75 MaxSpareThreads 250 ThreadsPerChild 25 MaxRequestWorkers 400 MaxConnectionsPerChild 0 </IfModule>

Cache Yapılandırması#

# mod_cache etkinleştir LoadModule cache_module modules/mod_cache.so LoadModule cache_disk_module modules/mod_cache_disk.so # Cache ayarları <IfModule mod_cache.c> CacheQuickHandler off CacheLock on CacheLockPath /tmp/mod_cache-lock CacheLockMaxAge 5 CacheIgnoreHeaders Set-Cookie </IfModule> <IfModule mod_cache_disk.c> CacheRoot /var/cache/apache2/mod_cache_disk CacheDirLevels 2 CacheDirLength 1 CacheMaxFileSize 1000000 </IfModule> # Statik dosyalar için cache <LocationMatch "\.(css|js|png|jpg|jpeg|gif|ico|svg)$"> CacheEnable disk ExpiresActive On ExpiresDefault "access plus 1 month" </LocationMatch>

Güvenlik Yapılandırması#

Temel Güvenlik Ayarları#

# Sunucu bilgilerini gizle ServerTokens Prod ServerSignature Off # Gereksiz modülleri devre dışı bırak <IfModule mod_autoindex.c> Options -Indexes </IfModule> # Güvenlik headers <IfModule mod_headers.c> Header always set X-Frame-Options "SAMEORIGIN" Header always set X-XSS-Protection "1; mode=block" Header always set X-Content-Type-Options "nosniff" Header always set Referrer-Policy "strict-origin-when-cross-origin" Header always set Content-Security-Policy "default-src 'self'" </IfModule> # Dosya yükleme sınırları LimitRequestBody 10485760 # 10MB # Timeout ayarları Timeout 60 KeepAliveTimeout 5

mod_security Kurulumu#

# ModSecurity kurulumu sudo apt install libapache2-mod-security2 # Modülü etkinleştir sudo a2enmod security2 # Temel yapılandırma sudo cp /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf # OWASP Core Rule Set indir cd /tmp wget https://github.com/coreruleset/coreruleset/archive/v3.3.0.tar.gz tar -xzf v3.3.0.tar.gz sudo mv coreruleset-3.3.0 /etc/modsecurity/crs sudo cp /etc/modsecurity/crs/crs-setup.conf.example /etc/modsecurity/crs/crs-setup.conf

Log Yönetimi#

Custom Log Format#

# Detaylı log formatı LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\" %D" combined_with_time CustomLog ${APACHE_LOG_DIR}/access.log combined_with_time # JSON format log LogFormat "{ \"time\":\"%t\", \"remoteIP\":\"%a\", \"host\":\"%V\", \"request\":\"%U\", \"query\":\"%q\", \"method\":\"%m\", \"status\":\"%>s\", \"userAgent\":\"%{User-agent}i\", \"referer\":\"%{Referer}i\" }" json CustomLog ${APACHE_LOG_DIR}/access_json.log json

Log Rotation#

# /etc/logrotate.d/apache2 /var/log/apache2/*.log { daily missingok rotate 52 compress delaycompress notifempty create 644 root adm sharedscripts postrotate if /bin/systemctl status apache2 > /dev/null ; then \ /bin/systemctl reload apache2 > /dev/null; \ fi; endscript }

Monitoring ve Troubleshooting#

Apache Status Modülü#

# mod_status etkinleştir LoadModule status_module modules/mod_status.so <Location "/server-status"> SetHandler server-status Require local Require ip 192.168.1 </Location> <Location "/server-info"> SetHandler server-info Require local </Location>

Performans İzleme#

# Aktif bağlantıları göster sudo netstat -tulpn | grep :80 # Apache process'lerini izle sudo ps aux | grep apache2 # Memory kullanımını kontrol et sudo apache2ctl status # Error log'u izle sudo tail -f /var/log/apache2/error.log # Access log analizi sudo tail -f /var/log/apache2/access.log | grep -E "(404|500)"

Yaygın Sorunlar ve Çözümleri#

  1. 403 Forbidden Hatası
# Dizin izinlerini kontrol et <Directory /var/www/example.com> Options +Indexes +FollowSymLinks AllowOverride All Require all granted </Directory>
  1. 500 Internal Server Error
# Error log'u kontrol et sudo tail -20 /var/log/apache2/error.log # Syntax hatası kontrolü sudo apache2ctl configtest
  1. Yavaş Performans
# KeepAlive ayarları KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 2 # MPM ayarlarını optimize et MaxRequestWorkers 400

Backup ve Restore#

Yapılandırma Yedekleme#

#!/bin/bash # Apache yapılandırma yedekleme scripti BACKUP_DIR="/backup/apache" DATE=$(date +%Y%m%d_%H%M%S) mkdir -p $BACKUP_DIR # Yapılandırma dosyalarını yedekle tar -czf $BACKUP_DIR/apache_config_$DATE.tar.gz \ /etc/apache2/ \ /var/www/ \ /etc/ssl/ # SSL sertifikalarını yedekle cp -r /etc/letsencrypt $BACKUP_DIR/letsencrypt_$DATE echo "Apache yapılandırması yedeklendi: $DATE"

Sonuç#

Apache HTTP Server, doğru yapılandırıldığında güçlü ve esnek bir web sunucusudur. Bu rehberde ele aldığımız konular:

  • Temel kurulum ve yapılandırma
  • Virtual host yönetimi
  • SSL sertifikası kurulumu
  • mod_rewrite ve .htaccess kullanımı
  • PHP entegrasyonu
  • Performans optimizasyonu
  • Güvenlik yapılandırması
  • Log yönetimi ve monitoring

Düzenli bakım, güvenlik güncellemeleri ve performans izleme ile Apache sunucunuzun optimal çalışmasını sağlayabilirsiniz.

Related Posts