Hey guys,
Good morning!

In this post, I will share very useful information related to the .htaccess file, which is the Apache HTTP server configuration file, which I have already made some posts about in this link. These tips I found on the blog http://www.deuzebranaweb.com.br/ and I thought the content was excellent and decided to share these little precious tips with you.

To create the rules below, open notepad or similar, save as “all files” and with the name .htaccess. It is worth mentioning that some codes will only work if certain extensions are enabled in Apache. If any code generates a 500 error, enable the corresponding module in Apache. And to avoid such errors, make the codes in conditional structures (), so the code will only be executed if the module is active.

Hiding the URL index

# se o seu site é feito em php, substitua os "html" pelo mesmo
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index\.html\ HTTP/
RewriteRule ^(([^/]+/)*)index\.html$ http://www.seusite.com.br/$1 [R=301,L]

Protecting your website against copying or misuse of files (such as php scripts, js, css, images)

#Neste caso, se alguém que não está na lista acima tentar usar as suas imagens direto do seu site ou usar os seus scripts, mostrará uma tela com erro e as imagens não serão mostradas.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://seusite.com.br/.*$ [NC]  #este site está liberado a usar (o seu site no caso)
RewriteCond %{HTTP_REFERER} !^http://www.seusite.com.br/.*$ [NC]  #este site está liberado a usar
RewriteCond %{HTTP_REFERER} !^http://www.google.com.br/.*$ [NC]  #liberar o google para usar as suas imagens
RewriteRule .*\.(jpg|jpeg|gif|png|bmp|php|js|swf)$ – [F,NC]

Block the .htaccess file from accessing the URL

<Files ~ "^\.(htaccess|htpasswd)$">
  deny from all
</Files>

Blocking specific files from access via URL

<files seuarquivo.php>
  order allow,deny
  deny from all
</files>

Set the default file upload order

By default, the file to be loaded when you type the website URL and open a web page is index.html. However, this can be easily changed as needed by changing the server's .htaccess file.

Using the code below, we define that the default page will be index.php. If this file does not exist, the next file in the list (index.htm) will be loaded and so on, until reaching the last file in the list (pagina.php). If this last file does not exist, Apache will reproduce an error in the browser of your website visitor (Error 403 – Forbidden).

## Pagina padrao ##
DirectoryIndex index.php index.htm index.html pagina.php

Increase PHP session time

<IfModule mod_php5.c>

    # Definir o tempo máximo de execucao do script para 30 mins (padrão: 60s)
    php_value max_execution_time 1800

    # Definir o tempo de expiração de sessao para 2 horas (padrão: 24 mins)
    php_value session.cookie_lifetime 7200
    php_value session.cache_expire 7200
    php_value session.gc_maxlifetime 7200

</IfModule>

Always put “www” in the URL

<IfModule mod_rewrite.c>
 
    RewriteEngine On
        
    # Redirecionar http://dominio.com.br para http://www.dominio.com.br
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,NE,L]
 
    # Retirar / no final do link
    RewriteCond %{HTTP_HOST} !^\. [NC]
    RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]
 
    # Remover o index.php
    RewriteCond %{THE_REQUEST} ^.*/index.php
    RewriteRule ^(.*)$ / [R=301,L]
    
</IfModule>

Compress website files to consume less bandwidth

<IfModule mod_deflate.c>
  <FilesMatch "\.(js|css|jpg|png|gif|ico|php|html|htm)$">
    <ifModule mod_filter.c>
      SetOutputFilter DEFLATE
      AddOutputFilterByType DEFLATE text/css text/javascript application/x-javascript text/html text/plain text/xml image/x-icon
    </IfModule>
  </FilesMatch>
</IfModule>

Enabling compression with DEFLATE

This is the easiest compression to configure on the server and is already enabled by default. It uses less server processing than GZip, but does not compress as much as it does.

<IfModule mod_deflate.c>

    # Compactar por tipo - html, text, css, xml
    AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml

    # Compactar por tipo - javascript
    AddOutputFilterByType DEFLATE application/x-javascript application/javascript text/javascript text/x-js text/x-javascript

    # Compactar por extensão
    AddOutputFilter DEFLATE js css htm html xml ttf eot

</IfModule>

Enabling compression with GZip

GZip is gaining a lot of space nowadays on the Web due to its great data compression power, drastically reducing page loading times, especially when we talk about mobile internet (3G) in Brazil, which is still very slow and precarious in many places. As it presents a high level of compression, it requires more processing than the DEFLATE compression method.

<IfModule mod_gzip.c>
    mod_gzip_on       Yes
    mod_gzip_dechunk  Yes
    mod_gzip_item_include file      \.(html?|txt|css|js|php|pl|ttf|eot)$
    mod_gzip_item_include handler   ^cgi-script$
    mod_gzip_item_include mime      ^text/.*
    mod_gzip_item_include mime      ^application/x-javascript.*
    mod_gzip_item_exclude mime      ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

Creating custom error pages

ErrorDocument 400 /sua-pagina-erro-400
ErrorDocument 404 /página-de-erro-404
ErrorDocument 500 /página-para-erro-500

Change the website's home (default) page

DirectoryIndex minhaoutrapagina.html
Redirecionamento 301 com htaccess
Redirect 301 /página-a-ser-movida  http://www.seusite.com.br/pagina-movida-para-ca

Block directory listing

# Impedir a listagem de arquivos no endereço www.seudominio.com/images/
IndexIgnore /images/*

# Impedir a listagem do próprio .htaccess e várias outras extensões de arquivos, além do arquivo teste.xls
IndexIgnore .htaccess *.php *.js *.css *.htm *.html *.log *.sql *.pdf *.swf *.rtf *.doc *.odt teste.xls

# Impedir a listagem de qualquer arquivo e diretório
Options -Indexes

Force the use of SSL

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://seu-site.com.br/$1 [R,L]

Disable case sensitive

CheckSpelling On
#agora a url PAGINA.HTML é igualmente acessada por pagina.html

Restricting access by IP

Order allow,deny
allow from 192.168.0.
deny from all
# Deixa a somente a INTRANET acessar
Order deny,allow
deny from 192.168.0.25
allow from all
# Deixa todo mundo acessar, menos o IP 192.168.0.25
Order deny, allow
deny from all
#bloquear geral

Redirect access from one website to another location

RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http(s)?://(www\.)?bloqueado.com.br.*$ [NC]
RewriteRule .* http://www.antispam.br [R,L]
#Se o site "bloqueado" mandar algum visitante para aqui, é redirecionado para o "antispam"

Regular expressions

#todos os arquivos de uma página serão redirecionados para outra
RewriteEngine on
RewriteRule ^pagina-antiga/(.*) http://www.novosite.com.br/pagina-antiga/$1
#redirecionar somente os arquivos terminados em php
RewriteEngine om
RewriteRule ^pagina-antiga/(.*)\.php http://www.novosite.com.br/pagina-antiga/$1.php
#redirecionar tudo de um site para outro
RedirectMatch permanent /(.*) http://www.novosite.com/$1

Remove URL extensions

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
#neste caso, estou retirando apenas o HTML

Force use of UTF-8 charset for files

<FilesMatch "\.(htm|html|css|js)$">
  AddDefaultCharset UTF-8
</FilesMatch>

Browser cache – Set expiration time (seconds)

<ifModule mod_expires.c>
  ExpiresActive On
  ExpiresDefault A0
  ExpiresByType image/gif A604800  
  ExpiresByType image/jpeg A604800
  ExpiresByType image/png A604800
  ExpiresByType text/css A604800
  ExpiresByType text/javascript A604800
  ExpiresByType application/x-javascript A604800
</ifModule>

Browser cache – Set cache control (seconds)

<IfModule mod_headers.c>
 <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|xml|woff)$">
 Header set Cache-Control "max-age=604800, public"
 Header append Vary User-Agent env=!dont-vary
 Header append Vary Accept-Encoding
 Header unset Pragma
 </FilesMatch>
</IfModule>

Browser cache – Force the use of the cache by disabling ETag

<IfModule mod_headers.c>
 Header unset Etag
 Header unset Last-Modified 
</IfModule>

Add new mimetypes

AddType application/x-endnote-connection enz AddType application/x-endnote-filter enf AddType application/x-spss-savefile sav 

Disable execution of certain Scripts

Options -ExecCGI
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi

Change the default language

DefaultLanguage en-US

Change default time zone

SetEnv TZ America/Indianapolis

Force download of certain files

AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4

Block request based on user-agent

SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT
SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT
Deny from env=HTTP_SAFE_BADBOT

That's it, folks!
I hope you enjoyed this post and until the next one.