Hello people,
Good Morning!
In this post, I will share useful information related to the .htaccess file, which is the Apache HTTP server configuration file, in which I have already made some posts about on this link. These tips I found on the blog http://www.deuzebranaweb.com.br/ and I found the content excellent and decided to share with you these little precious tips.
To create the rules below, open notepad or similar, save as “all files” and named .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 URL Indexing
1 2 3 4 5 | # 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 site from copying or misusing files (such as php, js, css, images)
1 2 3 4 5 6 | #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 .htaccess file from URL access
1 2 3 | <Files ~ "^\.(htaccess|htpasswd)$"> deny from all </Files> |
Blocking specific files against URL access
1 2 3 4 | <files seuarquivo.php> order allow,deny deny from all </files> |
Set default file upload order
By default, the file to upload 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 .htaccess file.
Using the code below, we set the default page to be index.php. If this file does not exist, the next file in the list (index.htm) will be loaded and so on until it reaches the last file in the list (page.php). If this last file does not exist, apache will reproduce an error in your site's visitor browser (Error 403 - Forbidden).
1 2 | ## Pagina padrao ## DirectoryIndex index.php index.htm index.html pagina.php |
Increase PHP session time
1 2 3 4 5 6 7 8 9 10 11 | <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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <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 site files to consume less bandwidth
1 2 3 4 5 6 7 8 | <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.
1 2 3 4 5 6 7 8 9 10 11 12 | <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 has been gaining a lot of space on the web today because of its great data compression power, reducing page load times dramatically, especially when we talk about mobile internet (3G) in Brazil, which is still very slow and precarious Many places. Because it has a high level of compression, it requires more processing than the DEFLATE compression method.
1 2 3 4 5 6 7 8 9 10 | <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
1 2 3 | ErrorDocument 400 /sua-pagina-erro-400 ErrorDocument 404 /página-de-erro-404 ErrorDocument 500 /página-para-erro-500 |
Change website homepage (default)
1 2 3 | 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
1 2 3 4 5 6 7 8 | # 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 SSL Usage
1 2 3 | RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://seu-site.com.br/$1 [R,L] |
Disable case sensitive
1 2 | CheckSpelling On #agora a url PAGINA.HTML é igualmente acessada por pagina.html |
Restricting IP Access
1 2 3 4 5 6 7 8 9 10 11 | 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 site to another place
1 2 3 4 | 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
1 2 3 4 5 6 7 8 | #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 extensions from URL
1 2 3 4 5 | 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
1 2 3 | <FilesMatch "\.(htm|html|css|js)$"> AddDefaultCharset UTF-8 </FilesMatch> |
Browser Cache - Set Expiration Time (seconds)
1 2 3 4 5 6 7 8 9 10 | <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)
1 2 3 4 5 6 7 8 | <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 caching - Force caching by disabling ETag
1 2 3 4 | <IfModule mod_headers.c> Header unset Etag Header unset Last-Modified </IfModule> |
Add new mimetypes
1 | AddType application/x-endnote-connection enz AddType application/x-endnote-filter enf AddType application/x-spss-savefile sav |
Disable Execution of Certain Scripts
1 2 | Options -ExecCGI AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi |
Change the default language
1 | DefaultLanguage en-US |
Change default time zone
1 | SetEnv TZ America/Indianapolis |
Force download certain files
1 | AddType application/octet-stream .avi .mpg .mov .pdf .xls .mp4 |
Block request based on user-agent
1 2 3 | 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 see you next time.
Hello, see if you can help me ... I installed Xampp (Windows) and I would like to know how I manage the apache log file, my log file is 50 MB and in the future I will have problems, it is possible to delimit a size and then of reaching the size, the auto log file recycle?
Another question how do I get the log file to register the network user who accesses a page in PHP?
Thank you!