Cheatsheet Apache
Servidor web HTTP robusto e extensível com .htaccess
Apache
25
cards found
Categories:
Versions:
Basic Configuration
Config Files
# Debian/Ubuntu:
/etc/apache2/apache2.conf
/etc/apache2/sites-available/
/etc/apache2/ports.conf
# CentOS/RHEL:
/etc/httpd/conf/httpd.conf
/etc/httpd/conf.d/
Config file locations.
CLI Commands
apachectl configtest # test config
apachectl graceful # soft reload
systemctl restart apache2
systemctl status apache2
a2ensite site.conf # enable site
a2dissite site.conf # disable
a2enmod rewrite # enable module
Manage the service.
Essential Modules
a2enmod rewrite # URL rewrite
a2enmod ssl # HTTPS
a2enmod headers # custom headers
a2enmod proxy # reverse proxy
a2enmod proxy_http # HTTP proxy
a2enmod expires # cache headers
Enable features.
Main Directives
ServerRoot "/etc/apache2"
Listen 80
Listen 443
DocumentRoot "/var/www/html"
ServerName example.com
ServerAdmin admin@example.com
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
Global configuration.
Virtual Hosts
Basic Virtual Host
<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com
DocumentRoot /var/www/example
<Directory /var/www/example>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Configure a domain.
Multiple Sites
<VirtualHost *:80>
ServerName app1.com
DocumentRoot /var/www/app1
</VirtualHost>
<VirtualHost *:80>
ServerName app2.com
DocumentRoot /var/www/app2
</VirtualHost>
Several domains on the same server.
Directory and Permissions
<Directory /var/www/app>
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
<Directory /var/www/app/private>
Require ip 192.168.1.0/24
</Directory>
Control access per folder.
Alias and Subdirectories
Alias /docs /var/www/documentation
<Directory /var/www/documentation>
Require all granted
</Directory>
# Access at: example.com/docs/
Map paths.
.htaccess
Basic Structure
# .htaccess in the project root
RewriteEngine On
# Redirect to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Per-directory config.
Cache and Compression
# Static file caching:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
</IfModule>
# Gzip:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/json
</IfModule>
Performance.
SPA (React/Vue)
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
Frontend routing.
Laravel / PHP
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
# Or in public/.htaccess:
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
Routing for PHP.
Block and Protect
# Block access to files:
<FilesMatch "\.(env|gitignore|md)$">
Require all denied
</FilesMatch>
# Protect .git:
RedirectMatch 404 /\.git
# Disable listing:
Options -Indexes
Security via .htaccess.
mod_rewrite
RewriteRule Syntax
RewriteRule Pattern Substitution [Flags]
# Common flags:
[L] # Last (stop here)
[R=301] # Permanent redirect
[R=302] # Temporary redirect
[NC] # No Case (ignore case)
[QSA] # Query String Append
Rule structure.
RewriteCond
# Conditions (before the Rule):
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/api/
Conditions for rules.
Practical Examples
# Remove www:
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# Friendly URL:
RewriteRule ^product/([0-9]+)$ product.php?id=$1 [L]
# Remove .html:
RewriteRule ^([^\.]+)$ $1.html [L]
Common use cases.
Redirects
# Simple redirect:
Redirect 301 /old /new
RedirectMatch 301 ^/blog/(.*)$ /articles/$1
# Redirect with Rewrite:
RewriteRule ^/old/(.*)$ /new/$1 [R=301,L]
# Conditional redirect:
RewriteCond %{HTTP_HOST} ^old\.com$
RewriteRule ^(.*)$ https://new.com/$1 [R=301,L]
Redirections.
Security
SSL / HTTPS
<VirtualHost *:443>
ServerName example.com
SSLEngine on
SSLCertificateFile /etc/ssl/cert.pem
SSLCertificateKeyFile /etc/ssl/key.pem
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite HIGH:!aNULL:!MD5
</VirtualHost>
Configure TLS.
Security Headers
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security \
"max-age=31536000; includeSubDomains"
Header always set Referrer-Policy "strict-origin-when-cross-origin"
HTTP header protection.
Hide Information
# httpd.conf / apache2.conf:
ServerTokens Prod
ServerSignature Off
# Remove version header:
Header unset X-Powered-By
# Disable TRACE:
TraceEnable Off
Minimize exposure.
Protect Directories
# Basic auth:
<Directory /var/www/admin>
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
</Directory>
# Create: htpasswd -c .htpasswd user
Per-folder authentication.
Advanced
Reverse Proxy
a2enmod proxy proxy_http
<VirtualHost *:80>
ServerName app.example.com
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
</VirtualHost>
Proxy for Node/Python.
WebSocket Proxy
a2enmod proxy_wstunnel
ProxyPass /ws ws://127.0.0.1:8080/ws
ProxyPassReverse /ws ws://127.0.0.1:8080/ws
# Or with Rewrite:
RewriteCond %{HTTP:Upgrade} websocket [NC]
RewriteRule /ws/(.*) ws://127.0.0.1:8080/$1 [P,L]
WebSocket support.
MPM and Performance
# /etc/apache2/mods-available/mpm_event.conf
<IfModule mpm_event_module>
StartServers 4
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</IfModule>
Process tuning.
Debug and Logs
# Log level:
LogLevel warn # debug, info, notice, warn, error
# View active config:
apachectl -S # virtual hosts
apachectl -M # active modules
apachectl -t -D DUMP_VHOSTS
# Custom log:
LogFormat "%h %l %u %t \"%r\" %>s %b" common
Diagnostics and logging.