Hero Image

Apache .htaccess and mod_rewrite on OpenBSD 7.5

Apache .htaccess and mod_rewrite on OpenBSD 7.5

Enable mod_rewrite

# Debian/Ubuntu:
a2enmod rewrite && systemctl restart apache2

# RHEL/AlmaLinux – already enabled in most configs
# Verify in /etc/httpd/conf.modules.d/00-base.conf:
# LoadModule rewrite_module modules/mod_rewrite.so

# Arch/Gentoo – uncomment LoadModule rewrite_module in httpd.conf

Allow .htaccess overrides

In your virtual host or <Directory> block:

<Directory /var/www/example.com/html>
    AllowOverride All
    Require all granted
</Directory>

Common .htaccess recipes

Force HTTPS

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Remove www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,R=301]

Pretty URLs (CMS front controller)

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Block access to dotfiles

<FilesMatch "^\.">
    Require all denied
</FilesMatch>

Custom error pages

ErrorDocument 404 /404.html
ErrorDocument 500 /500.html

Gzip compression

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript
    AddOutputFilterByType DEFLATE application/json application/xml
</IfModule>

Browser caching

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg  "access plus 1 year"
    ExpiresByType image/png  "access plus 1 year"
    ExpiresByType text/css   "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>