Apache Complete Cheatsheet! Everything You Need To Know

Apache Cheatsheet

Table of contents for this Cheat sheet: 301 Redirect a single URL in .htaccess to a new locationForce trailing slash (redirect if no trailing slash exists) in .htaccessHow to add the default charset to UTF-8 in .htaccessHow to block access to certain referrers in Apache using .htaccessHow to block an IP address in .htaccessHow to block an IP range based on CIDR in Apache with .htaccessHow to block IP addresses in Apache by using regular expressions (regex) in .htaccessHow to block IPv6 IP addresses in .htaccessHow to block multiple IP addresses in .htaccessHow to disable file hotlinking in Apache with .htaccessHow to Enable Directory Listings in Apache with .htaccessHow to enable the rewrite engine in .htaccess?How to force gzip compression in Apache with .htaccessHow to force non www in htaccessHow to force SSL in Apache's .htaccess?How to Force www or non-www in htaccessHow to have a whitelist of IP addresses that can access files in .htaccessHow to hide certain file types from directory listingsHow to hide directory listing in .htaccess?How to hide the server signature (hide Apache info) from HTTP headers with .htaccessHow to make Apache force download of files (in .htaccess)How to redirect your website to a new domain/location in .htaccessHow to remove .php from the end of URLs with .htaccessHow to set custom HTTP headers in Apache (by editing .htaccess)How to set environmental variables in your .htaccess fileHow to set the Expires header in .htaccessHow to set the timezone to UTC in .htaccessHow to set up an alias to map one directory to another destinationHow to set up an alias to map one directory to another destinationHow to set up custom error pages in .htaccess for your Apache server (ErrorDocument)Point all requests to one PHP fileRemove trailing slash (redirect to remove trailing slash) in .htaccessSet PHP config Variables (like ini_set) with .htaccessWhat are Apache MPMs?What is WordPress default Apache .htaccess rules?

301 Redirect a single URL in .htaccess to a new location

  1. Redirect 301 /old-url http://www.example.com/new-url
View More Details (and 9 discussions about this topic) Here...

Force trailing slash (redirect if no trailing slash exists) in .htaccess

If you want to redirect from http://example.com/test to http://example.com/test/ then you can use the following .htaccess code:

  1. RewriteCond %{REQUEST_URI} \/+[^\.]+$
  2. RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 5 discussions about this topic) Here...

How to add the default charset to UTF-8 in .htaccess

If you want to define the default charset to UTF-8, you can do this in one line in .htaccess

  1. AddDefaultCharset UTF-8
View More Details (and 7 discussions about this topic) Here...

How to block access to certain referrers in Apache using .htaccess

Here are the rules you need if you want to block access to any request that contains a certain referring URL

  1. RewriteCond %{HTTP_REFERER} bad-site-linking-to-your\.com [NC,OR]
  2. RewriteCond %{HTTP_REFERER} another-bad-site-linking-to-you\.com [NC]
  3. RewriteRule .* - [F]
View More Details (and 12 discussions about this topic) Here...

How to block an IP address in .htaccess

If you have a specific IP address that you want to block access to, you can do this in Apache's .htaccess with the following code

  1. Deny from x.x.x.x

(replace x.x.x.x with the actual IP address)

View More Details (and 4 discussions about this topic) Here...

How to block an IP range based on CIDR in Apache with .htaccess

If you have a CIDR range that you want to block with .htaccess, use the following format:

  1. Deny from 111.222.111.0/24
View More Details (and 4 discussions about this topic) Here...

How to block IP addresses in Apache by using regular expressions (regex) in .htaccess

You can use regex in your .htaccess rules. You have to utilize a Rewrite Rule (so make sure you have the rewrite engine turned on) to do this block.

  1. <IfModule mod_rewrite.c>
  2.     RewriteCond %{REMOTE_ADDR} ^123.111.222.(1[0-9]|3[3-6]|9[0-9]$ [OR]
  3.     RewriteCond %{REMOTE_ADDR} ^123.222.111.1([0-2][0-9])$
  4.     RewriteRule .* - [F]
  5. <\/IfModule>

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 7 discussions about this topic) Here...

How to block IPv6 IP addresses in .htaccess

Blocking IPv6 IP addresses is the same as blocking IPv4 addresses in .htaccess

  1. Deny from 2001:0db8:85a3:0000:0000:8a2e:0370:7334
View More Details (and 9 discussions about this topic) Here...

How to block multiple IP addresses in .htaccess

If you need to block more than one IP address you can do this quite easily. Put each one of the IP addresses next to each other with a space in between.

  1. Deny from x.x.x.x y.y.y.y z.z.z.z

(Replace the x.x.x.x / y.y.y.y / z.z.z.z with the IP addresses that you wish to block access to)

View More Details (and 10 discussions about this topic) Here...

How to disable file hotlinking in Apache with .htaccess

If you want to ensure that every image requested comes with a HTTP referrer of your own site's URL then this anti image hotlinking .htaccess rule will help you out:

  1. RewriteCond %{HTTP_REFERER} !^$
  2. RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?YOURSITE.com [NC]
  3. RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 3 discussions about this topic) Here...

How to Enable Directory Listings in Apache with .htaccess

If you want to show the contents of directories then you can add this to your .htaccess rules

  1. Options All +Indexes
View More Details (and 5 discussions about this topic) Here...

How to enable the rewrite engine in .htaccess?

Before you can use rewrite rules in .htaccess you must enable the rewrite engine.

To enable the rewrite engine in .htaccess you must add this to your .htaccess file:

  1. RewriteEngine On
View More Details (and 12 discussions about this topic) Here...

How to force gzip compression in Apache with .htaccess

You can force Apache to compress data before sending it by adding a few lines of code to your .htaccess file.

  1. <ifModule mod_gzip.c>
  2.     mod_gzip_on Yes
  3.     mod_gzip_dechunk Yes
  4.  
  5.     mod_gzip_item_include file .(html?|txt|css|js|php)$
  6.     mod_gzip_item_include mime ^application/x-javascript.*
  7.     mod_gzip_item_include mime ^text/.*
  8.     mod_gzip_item_exclude mime ^image/.*
  9.  
  10.     mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
  11. <\/ifModule>
View More Details (and 7 discussions about this topic) Here...

How to force non www in htaccess

If you want to automatically redirect from www to non-www of your website, in .htaccess then you can add this code (edit your domain as required) to your .htaccess

  1. #Force non-www:
  2. RewriteEngine on
  3. RewriteCond %{HTTP_HOST} ^www\.YOURSITE\.com [NC]
  4. RewriteRule ^(.*)$ http://YOURSITE.com/$1 [L,R=301]

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 9 discussions about this topic) Here...

How to force SSL in Apache's .htaccess?

If you need to enable SSL (https) URLs in htaccess (redirect non SSL to SSL, or redirect http to https in .htaccess) then you should use this code:

  1. RewriteCond %{HTTPS} !=on
  2. RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

If you want to redirect to https AND force www then you can use the following code:

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

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 4 discussions about this topic) Here...

How to Force www or non-www in htaccess

If you want to redirect non-www requests to the www URL of your website (i.e. redirect from http://example.com to http://www.example.com/) then you can do this with a few lines in your .htaccess file

  1. RewriteCond %{HTTP_HOST} !^$
  2. RewriteCond %{HTTP_HOST} !^www\. [NC]
  3. RewriteCond %{HTTPS}s ^on(s)|
  4. RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Don't forget to enable the rewrite engine!

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 7 discussions about this topic) Here...

How to have a whitelist of IP addresses that can access files in .htaccess

If you want Apache to only allow access to files/directories that match a set of IP addresses you can use this:

  1. <Files admin_panel.php>
  2. Order deny,allow
  3. Deny from all
  4. Allow from x.x.x.x localhost
  5. </Files>

Remember to change admin_panel.php and X.X.X.X to your details

View More Details (and 7 discussions about this topic) Here...

How to hide certain file types from directory listings

If you have Directory Listings enabled but want to hide certain file types from being shown you can use these htaccess config lines

  1. IndexIgnore *.backup *.zip *.gz
View More Details (and 11 discussions about this topic) Here...

How to hide directory listing in .htaccess?

  1. Options -Indexes
View More Details (and 11 discussions about this topic) Here...

How to hide the server signature (hide Apache info) from HTTP headers with .htaccess

If you don't want to publicly announce in the HTTP headers what version of Apache that your website is using, add this code to hide it:

  1. ServerSignature Off
View More Details (and 10 discussions about this topic) Here...

How to make Apache force download of files (in .htaccess)

If you want to force the download of files (octet-stream), you can use this code. Edit the file types as required.

  1. AddType application/octet-stream .doc .docx .xls .pdf

You can use this to force PDFs to download and not show in the browser:

  1. AddType application/octet-stream .pdf

If you want to force other file types (such as Word Document, Excel, etc) just edit the file type

View More Details (and 6 discussions about this topic) Here...

How to redirect your website to a new domain/location in .htaccess

If you need to move domains and want to 301 redirect all old URLs to the new domain/location, use the following .htaccess code

  1. Redirect 301 / http://your-new-domain.com/
View More Details (and 6 discussions about this topic) Here...

How to remove .php from the end of URLs with .htaccess

If you have files such as hello.php and you want users to be able to go to yoursite.com/hello, use the following code:

  1. RewriteCond %{SCRIPT_FILENAME} !-d
  2. RewriteRule ^([^.]+)$ $1.php [NC,L]

A request to http://yoursite/asdf will try and use the file /asdf.php.

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 5 discussions about this topic) Here...

How to set custom HTTP headers in Apache (by editing .htaccess)

  1. Header always set YOURHEADERNAME "Your Header Value"
  2. Header always set Referrer-Policy "strict-origin-when-cross-origin"
  3. Header set Content-Language "en-gb"
View More Details (and 9 discussions about this topic) Here...

How to set environmental variables in your .htaccess file

Setting env vars is easy in your .htaccess file.

  1. SetEnv ENV_VAR_NAME 'env var value'

(you must enable mod_env in Apache for this to work)

You can access these environment variables in PHP with this code:

  1. var_dump(getenv('ENV_VAR_NAME'));
View More Details (and 12 discussions about this topic) Here...

How to set the Expires header in .htaccess

Setting the expires header is a great way to enable browser based caching, which should help make some pages load faster. Here is the code how to do it in .htaccess.

  1. <IfModule mod_expires.c>
  2.         ExpiresActive on
  3.  
  4.         ExpiresDefault                                    "access plus 1 month"
  5.  
  6.  
  7.     # TEXT STUFF
  8.        ExpiresByType text/css                            "access plus 1 year"
  9.         ExpiresByType application/json                    "access plus 0 seconds"
  10.         ExpiresByType application/xml                     "access plus 0 seconds"
  11.         ExpiresByType text/xml                            "access plus 0 seconds"
  12.  
  13.     # FAVICON
  14.        ExpiresByType image/x-icon                        "access plus 1 week"
  15.  
  16.     # HTML
  17.        ExpiresByType text/html                           "access plus 0 seconds"
  18.  
  19.     # JAVASCRIPT
  20.        ExpiresByType application/javascript              "access plus 1 year"
  21.  
  22.     # FONTS
  23.        ExpiresByType application/font-woff2              "access plus 1 month"
  24.         ExpiresByType application/font-woff               "access plus 1 month"
  25.         ExpiresByType application/vnd.ms-fontobject       "access plus 1 month"
  26.         ExpiresByType application/x-font-ttf              "access plus 1 month"
  27.         ExpiresByType font/opentype                       "access plus 1 month"
  28.         ExpiresByType image/svg+xml                       "access plus 1 month"
  29.  
  30.  
  31.         ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
  32.         ExpiresByType text/cache-manifest                 "access plus 0 seconds"
  33.  
  34.         ExpiresByType audio/ogg                           "access plus 1 month"
  35.         ExpiresByType image/gif                           "access plus 1 month"
  36.         ExpiresByType image/jpeg                          "access plus 1 month"
  37.         ExpiresByType image/png                           "access plus 1 month"
  38.         ExpiresByType video/mp4                           "access plus 1 month"
  39.         ExpiresByType video/ogg                           "access plus 1 month"
  40.         ExpiresByType video/webm                          "access plus 1 month"
  41.  
  42.         ExpiresByType application/atom+xml                "access plus 1 hour"
  43.         ExpiresByType application/rss+xml                 "access plus 1 hour"
  44.  
  45. </IfModule>
View More Details (and 10 discussions about this topic) Here...

How to set the timezone to UTC in .htaccess

Use the following code in your .htaccess to change the timezone to UTC. You can also change 'UTC' to another valid time zone'

  1. SetEnv TZ UTC
View More Details (and 8 discussions about this topic) Here...

How to set up an alias to map one directory to another destination

  1. RewriteRule ^from/(.*) to/$1

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 8 discussions about this topic) Here...

How to set up an alias to map one directory to another destination

  1. RewriteRule ^from/(.*) to/$1

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 3 discussions about this topic) Here...

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

If you want to set up a custom error page (for example when a 404 error happens) you can define what file to serve in your .htaccess file

  1. ErrorDocument 500 "Show a plain text message"
  2. ErrorDocument 401 http://redirect.com/to/a/url.html
  3. ErrorDocument 404 /error_files/your_404_error_file.htm
View More Details (and 3 discussions about this topic) Here...

Point all requests to one PHP file

If you want every request to be routed through a main file (similar to how WordPress and a lot of frameworks do it) then you can use this code, and every request that isn't an existing file or directory (so users can still access .css or images):

  1. RewriteCond %{REQUEST_FILENAME} !-f
  2. RewriteCond %{REQUEST_FILENAME} !-d
  3. RewriteRule ^([^?]*)$ /index.php [NC,L,QSA]

Remember to create the /index.php file too.

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 8 discussions about this topic) Here...

Remove trailing slash (redirect to remove trailing slash) in .htaccess

If you want to redirect from http://example.com/test/ to http://example.com/test (i.e. remove the slash at the end of URLs) then you can use the following .htaccess code:

  1. RewriteCond %{REQUEST_FILENAME} !-d
  2. RewriteRule ^(.*)/$ /$1 [R=301,L]

This will 301 redirect to the non trailing slash version of the page

Don't forget that you will probably need to enable the rewrite engine for these rules to work. Click the button below to find out how to do this.

View More Details (and 9 discussions about this topic) Here...

Set PHP config Variables (like ini_set) with .htaccess

If you need to set some PHP config variables (the same as in php.ini or via ini_set()) you can do this in .htaccess

  1. php_value upload_max_filesize 150M
  2. php_value  include_path  ".:/usr/local/lib/php"
  3. php_value error_log  "/log/location/php_errors.log"

If you need to switch something from on to off (true/false) then you must use php_flag:

  1. php_flag display_errors off

If apache is run in CGI mode this will not work.

View More Details (and 4 discussions about this topic) Here...

What are Apache MPMs?

Since Apache 2, Multi-Processing Modules (MPMs) have existed. They are modules that change how the Apache servers handles requests and listens to connections.

Common Apache MPMs include prefork, worker, and event. There are different MPMs for different operating systems - these three are for Unix based systems. See the list here for other operating system's MPMs.

How to decide what MPM your Unix-like system (i.e. Linux, BSD, Mac OS, etc) will use?

In the case of Unix, the decision as to which MPM is installed is based on two questions:

1. Does the system support threads?

2. Does the system support thread-safe polling (Specifically, the kqueue and epoll functions)?

If the answer to both questions is 'yes', the default MPM is event.

If The answer to #1 is 'yes', but the answer to #2 is 'no', the default will be worker.

If the answer to both questions is 'no', then the default MPM will be prefork.

In practical terms, this means that the default will almost always be event, as all modern operating systems support these two features.

How to check what MPM your installation of Apache is using?

Run the following command:

httpd -V | grep -i 'mpm'

The output from my Mac computer:

Server MPM:     prefork

The output from my linux VM:

Server MPM:     event

What is the prefork MPM? The preform module let's Apache work in a non-threaded, pre-forking way. Every one of the child processes that Apache has will have one single thread, and only processes one request at a time. It is the default type of MPM. This MPM is thread safe.

What is the Event Apache MPM? The Event MPM uses less resources than the other two described on this page. Each process can contain multiple threads. However, each thread can handle more than one task at a time. The event MPM works with Apache 2.2, however it is not fully compatible. It is recommended to use a minimum of Apache 2.4 when using the event MPM. (But there are plenty of high traffic sites using the event MPM and 2.2 without problems).

What is the worker mpm? The worker MPM lets Apache run as a multi threaded, multi process server. Each child process can have more than one thread. This means that Apache can handle a greater number of requests, while using fewer resources than the prefork MPM. The Worker MPM is commonly used with high traffic web servers on more recent versions of Apache. This MPM is not thread safe.

View More Details (and 11 discussions about this topic) Here...

What is WordPress default Apache .htaccess rules?

Messed up your WordPress .htaccess file? Here is the default one for most configurations:

  1. # BEGIN WordPress
  2. <IfModule mod_rewrite.c>
  3. RewriteEngine On
  4. RewriteBase /
  5. RewriteRule ^index\.php$ - [L]
  6. RewriteCond %{REQUEST_FILENAME} !-f
  7. RewriteCond %{REQUEST_FILENAME} !-d
  8. RewriteRule . /index.php [L]
  9. <\/IfModule>
  10.  
  11. # END WordPress
View More Details (and 8 discussions about this topic) Here...