Skip to main content

Apache URL rewrite examples.

Options -Indexes +FollowSymLinks

RewriteEngine On

##### Add WWW ###############################################
RewriteCond %{HTTP_HOST} ^domain.com$ [NC]
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]

##### Remove query string ###################################
RewriteCond %{QUERY_STRING} .
RewriteRule ^(.*)$ http://www.domain.com/$1? [L]

##### Remove trailing question mark #########################
RewriteCond %{THE_REQUEST} ? HTTP [NC]
RewriteRule .? http://www.domain.com%{REQUEST_URI}? [R=301,L]

##### Remove trailing index file ############################
RewriteCond %{THE_REQUEST} /index.php HTTP [NC]
RewriteRule (.*)index.php$ /$1 [R=301,L]

##### Add trailing slash ####################################
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.domain.com/$1/ [R=301,L]

##### Deny access to htaccess ###############################
<files .htaccess>
    order allow,deny
    deny from all
</files>

##### Cache media files #####################################
<filesMatch "\.(flv|gif|jpg|jpeg|png|ico|swf|js|css)$">
    Header set Cache-Control "max-age=2592000, public"
</filesMatch>

##### Don't cache dynamic pages #############################
<filesMatch ".(php|cgi)$">
    Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
</filesMatch>