Skip to content

Instantly share code, notes, and snippets.

@AntoOnline
Last active April 29, 2023 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AntoOnline/9b26f1a5633ab20869f0eee72ac475f2 to your computer and use it in GitHub Desktop.
Save AntoOnline/9b26f1a5633ab20869f0eee72ac475f2 to your computer and use it in GitHub Desktop.
Useful htaccess Examples

.htaccess Cheat Sheet

Basic Redirects

301 Redirect (Permanent Redirect)

Redirect 301 /old-page.html /new-page.html

302 Redirect (Temporary Redirect)

Redirect 302 /old-page.html /new-page.html

Rewrite URLs

Enable Rewrite Engine

RewriteEngine On

Remove .php Extension

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)$ $1.php [L]

Redirect HTTP to HTTPS

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Access Control

Block an IP Address

Order Allow,Deny
Deny from 192.168.1.1
Allow from all

Allow Only Specified IP Addresses

Order Deny,Allow
Deny from all
Allow from 192.168.1.1

Cache Control

Set Cache Expiration

<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpg "access 1 month"
  ExpiresByType image/jpeg "access 1 month"
  ExpiresByType image/gif "access 1 month"
  ExpiresByType image/png "access 1 month"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/html "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>

Custom Error Pages

Custom 404 Error Page

ErrorDocument 404 /404.html

This cheat sheet provides a quick reference for someone new to .htaccess, covering basic redirects, URL rewriting, access control, cache control, and custom error pages.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment