Clean URLs with Apache httpd

a la Caddy

Caddy server let’s you easily define implicit extensions for your server URLs. Check ext directive in it’s documentation.

Get the same result in apache httpd using rewrite rules

Configuration snippet
RewriteEngine On
# Auto ext, clean URLs
# -----
# .html
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !.*\.html$
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [NC,L]
# .php
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !.*\.php$
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [NC,L]

The story: If (1) the URI does not already end with the extension and (2) if it is not a folder with the same name and (3) if the file with the added extension actually exists, then it adds the extension

Later edit:  If the folder exists the rewriting is not done and therefore the index.html or index.php in the folder is served. If you want the file plus the added extention to have precedence over folder, comment out out the 2nd condition.

flag L|last stop processing rules after match. If you have other rules you need applied, remove it!

flag NC|nocase case-insensitive matching

Use the config snippet per VirtualHost. Or add it to your server global rewrite rules. Usually it’s the /etc/apache2/mods-enabled/rewrite.conf file. Don’t forget about RewriteOptions Inherit in your VirtualHost if you use the global configuration.

— tried and works with Apache 2.4

Leave a Reply

Your email address will not be published. Required fields are marked *