Vai al contenuto
Home » IL Blog del mondo IRC e Linux » htaccess file codici utili

htaccess file codici utili

htaccess snippets

Una serie di brevi codici da inserire ed usare nel vostro file htaccess.

AVVETRENZE: Usare con cautela. Ricordate di fare sempre una copia del file .htaccess originale.

 

Redirect 301 tramite htaccess

Questo è il modo più pulito per reindirizzare un URL. Veloce, facile e compatibile con i motori di ricerca. Ricorda che le cose HTAccess sono solo per i server Apache. Se vuoi imparare ad installare un server apache leggi questa guida.

 

Reindirizzamento di una singola pagina

Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html http://www.yoursite.com/folder/

Reindirizzamento di un intero sito

In questo modo lo fa con i collegamenti intatti . Cioè www.oldsite.com/some/crazy/link.html diventerà www.newsite.com/some/crazy/link.html. Questo è estremamente utile quando stai solo “spostando” un sito su un nuovo dominio. Inseriscilo nel VECCHIO sito:

Redirect 301 / http://newsite.com/

Reindrizzare tutti i vecchi url dopo aver cambiato il premalink

Per quelli che usano wordpress e che hanno imposto il premalink su nome e data , insomma che hanno url  dove è riportata la data dell’ articolo piu il nome dell’articolo e vogliono liberarsi della date nell’url, basta cambiare il premalink in impostazioni di wordpress, ma subito dopo deve creare una direttiva nel file htaccess che renidrizzi tutti gli url vecchi ai nuovi senza la data.

La direttiva è la seguente:

RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(?!page/)(.+)$ http://www.tuosito.it/$4

Questa direttiva funziona nel caso in cui passi da url con data e nome del post a url con solo nome del post

RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(?!page/)(.+)$ http://www.tuosito.it.com/$3

Questa direttiva è nel caso tu passi dalla struttura dell’url MESE e NOME DEL POST a solo Nome del post

RedirectMatch 301 ^/<category>/(.*)$ http://www.tuosito.it/$1

La terza direttiva che vedete è nel caso volessi passare dalla struttura url categoria-postname a solo postname (nome del post in Italiano)

RedirectMatch 301 ^/archives/(\d+)$ http://www.tuosito.it/?p=$1

La quarta ed ultima direttiva invece deve usarla chi vuole passare da una struttura url di tipo ARCHIVI/ID-POST a solo Postname.


Compressione Gzip attiva

La compressione riduce i tempi di risposta riducendo la dimensione della risposta HTTP. Gzip è il metodo di compressione più popolare ed efficace attualmente disponibile e generalmente riduce la dimensione della risposta di circa il 70%.

Nel 2009, il 90% del traffico internet viaggiava attraverso browser che lo supportavano. Gzip. Oggi :

Tutti i browser moderni supportano e negoziano automaticamente la compressione GZIP per tutte le richieste HTTP: il nostro compito è garantire che il server sia correttamente configurato per servire la risorsa compressa quando richiesto dal client.

Su un server basato su Apache, puoi farlo tramite il file .htaccess:

# BEGIN GZIP
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript
</ifmodule>
# END GZIP

Questo è essenzialmente un elenco di tipi MIME a cui verrà applicato gzipping. Sentiti libero di modificare l’elenco con tutte le risorse basate su testo che servi.

Il progetto HTML5 Boilerplate offre configurazioni server per tutti i server più diffusi. Questa è la sua versione per .htaccess

<IfModule mod_filter.c>
    AddOutputFilterByType DEFLATE "application/atom+xml" \
                                  "application/javascript" \
                                  "application/json" \
                                  "application/ld+json" \
                                  "application/manifest+json" \
                                  "application/rdf+xml" \
                                  "application/rss+xml" \
                                  "application/schema+json" \
                                  "application/vnd.geo+json" \
                                  "application/vnd.ms-fontobject" \
                                  "application/x-font-ttf" \
                                  "application/x-javascript" \
                                  "application/x-web-app-manifest+json" \
                                  "application/xhtml+xml" \
                                  "application/xml" \
                                  "font/eot" \
                                  "font/opentype" \
                                  "image/bmp" \
                                  "image/svg+xml" \
                                  "image/vnd.microsoft.icon" \
                                  "image/x-icon" \
                                  "text/cache-manifest" \
                                  "text/css" \
                                  "text/html" \
                                  "text/javascript" \
                                  "text/plain" \
                                  "text/vcard" \
                                  "text/vnd.rim.location.xloc" \
                                  "text/vtt" \
                                  "text/x-component" \
                                  "text/x-cross-domain-policy" \
                                  "text/xml"

</IfModule>

Negare e consentire l’accesso grazie al .htaccess file

 

Nega tranne che da IP specifici

Order deny,allow
Deny from All
Allow from xxx.xxx.xxx.xxx
Allow from xxx.xxx.xxx.xxy

Consenti tranne che da IP specifici

Order deny,allow
Allow from All
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy

Forza HTTPS

RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Se hai un proxy davanti al tuo server che esegue la terminazione TLS:

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

 

Leggi questo articolo per conoscere la differenza tra https ed ftp.


Servi SVG con il tipo di contenuto corretto

Se stai cercando di utilizzare SVG come <img src="image.svg">o come CSS background-imagee il file è collegato correttamente e tutto sembra a posto, ma il browser non lo visualizza, potrebbe essere perché il tuo server lo sta servendo con un tipo di contenuto errato.

Aggiungi questo al tuo file .htaccess alla radice per risolverlo:

AddType image/svg+xml .svg .svgz

htaccess file modifiche

.htaccess per wordpress snippets


Scoraggia i lamer adolescenti con wp-config Redirect

Chi sono i lamer?

E-mail divertente da un lettore, che ho pensato sarebbe stata un buon post:

Questo è un reindirizzamento divertente. Ricevo una o due visite al giorno da gangster adolescenti che cercano di entrare nel mio server controllando se esiste un file wp-config che non è più la versione più recente. Ho ottenuto i migliori risultati di panico collegandomi all’agenzia russa di controspionaggio informatico.

NOTA: NON dovresti usarlo se stai EFFETTIVAMENTE usando WordPress. Inoltre, l’ho aggiornato all’FBI da quando quel sito russo è andato in tilt.

Redirect 301 /wp-config.php http://www.fbi.gov/

 


Pagine di errore personalizzate

ErrorDocument 400 /400.html
ErrorDocument 401 /401.html
ErrorDocument 403 /403.html
ErrorDocument 404 /404.html
ErrorDocument 405 /405.html
ErrorDocument 408 /408.html
ErrorDocument 414 /414.html
ErrorDocument 500 /500.html
ErrorDocument 502 /502.html
ErrorDocument 504 /504.html

E un modello PHP per gestire qualsiasi tipo di errore, se vuoi mantenerlo semplice:

<?php

$status=$_SERVER['REDIRECT_STATUS'];
$codes=array(
      400 => array('400 Bad Request', 'The request cannot be fulfilled due to bad syntax.'),
      401 => array('401 Login Error', 'It appears that the password and/or user-name you entered was incorrect.'),
      403 => array('403 Forbidden', 'Sorry, employees and staff only.'),
      404 => array('404 Missing', 'We\'re sorry, but the page you\'re looking for is missing, hiding, or maybe it moved somewhere else and forgot to tell you.'),
      405 => array('405 Method Not Allowed', 'The method specified in the Request-Line is not allowed for the specified resource.'),
      408 => array('408 Request Timeout', 'Your browser failed to send a request in the time allowed by the server.'),
      414 => array('414 URL To Long', 'The URL you entered is longer than the maximum length.'),
      500 => array('500 Internal Server Error', 'The request was unsuccessful due to an unexpected condition encountered by the server.'),
      502 => array('502 Bad Gateway', 'The server received an invalid response from the upstream server while trying to fulfill the request.'),
      504 => array('504 Gateway Timeout', 'The upstream server failed to send a request in the time allowed by the server.'),
);

$errortitle=$codes[$status][0];
$message=$codes[$status][1];

if($errortitle==false){
       $errortitle="Unknown Error";
       $message="An unknown error has occurred.";
}

?>
<!doctype html>
<html>
<head>
<title><?php echo("$errortitle");?></title>
<meta charset="utf-8">
</head>
<body>

<!-- Insert headers here. -->

<?php
echo('<h1>'.$errortitle.'</h1>');
echo('<p>'.$message.'</p>');
?>

<!-- Insert footers here. -->

</body>
</html>

 


Aggiungi / Anteponi file

Piuttosto che dover richiamare/includere un file di cui hai bisogno in ogni singola pagina, puoi farli anteporre automaticamente (in cima al file) o aggiungere automaticamente (in fondo al file) tramite il tuo file .htaccess.

php_value auto_prepend_file "/real/path/to/file/functions.php"
php_value auto_append_file "/real/path/to/file/footer.php"

 


URL delle sottodirectory Reindirizzamento interno alla stringa di query

L’URL nel browser sarebbe:

https://css-tricks.com/index.php/teachers/a/

La pagina effettiva resa dal server sarebbe:

https://css-tricks.com/index.php?search=teachers&sort=a

RewriteEngine on
RewriteRule ^index/([^/]+)/([^/]+).php /page.php?search=$1&sort=$2 [NC]

 


Htaccess Registrazione errori PHP

Registra gli errori in un file ed evita di mostrarli all’utente. Assicurati che il file esista e che tu sia in grado di scriverci sopra.

# display no errs to user
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log to file
php_flag log_errors on
php_value error_log /location/to/php_error.log

 


Rimuovi l’estensione del file dagli URL

RewriteRule ^about$ about.php [L]

Questo farà in modo che http://example.com/about.php possa essere caricato su http://example.com/about


Consenti URL singolo attraverso la protezione con password .htaccess

Questo codice è utile per le configurazioni multiambiente (staging, produzione, ecc.) ti consente di mantenere sincronizzati i tuoi file htaccess mantenendo un htpasswd sul tuo ambiente di sviluppo o qualsiasi cosa tranne l’ambiente live.

#allows a single uri through the .htaccess password protection
SetEnvIf Request_URI "/testing_uri$" test_uri

#allows everything if its on a certain host
SetEnvIf HOST "^testing.yoursite.com" testing_url
SetEnvIf HOST "^yoursite.com" live_url
Order Deny,Allow

AuthName "Restricted Area"
AuthType Basic
AuthUserFile /path/to/your/.htpasswd
AuthGroupFile /
Require valid-user

#Allow valid-user
Deny from all
Allow from env=test_uri
Allow from env=testing_url
Allow from env=live_url
Satisfy any

 


Cartelle protette da password

Inserisci il file .htaccess nella directory che stai cercando di proteggere:

AuthType Basic
AuthName "This Area is Password Protected"
AuthUserFile /full/path/to/.htpasswd
Require valid-user

Idealmente, il file .htpasswd non si troverà in una directory pubblica. Metti questo qui:

chriscoyier:$apr1$O/BJv...$vIHV9Q7ySPkw6Mv6Kd/ZE/

Questo è solo un esempio, puoi creare il codice per il tuo nome utente e password univoci qui .

Si noti che anche tutte le sottodirectory di questa directory saranno protette da password da questo stesso sistema.


Forza set di caratteri utf-8

Se non è possibile modificare la configurazione del server Apache, utilizzare questo codice per forzare la decodifica della pagina in utf-8.

AddDefaultCharset utf-8

 


Pagina index directory diversa

Normalmente index.html o index.php è la pagina predefinita che un server serve quando si visita una directory senza specificare un nome file. Puoi cambiarlo con .htaccess:

DirectoryIndex index2.html

 


Impedisci l’hotlinking delle immagini dal tuo sito tramite .htaccess

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?yourdomain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpg|gif|bmp|png)$ /images/dontsteal.jpg [L]

Le immagini collegate da un sito diverso dal tuo sito Web vengono reindirizzate a una grafica personalizzata. Tieni presente, tuttavia, che ciò influirebbe anche sulle persone che leggono i post tramite i lettori RSS.

Consenti anche i motori di ricerca

RewriteCond %{HTTP_REFERER} !^http://(.+\.)?mydomain\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?google\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?google\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?bing\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?bing\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?yahoo\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?(.*\.)?yahoo\.(.+)/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|png)$ /transparent.gif [L]

 


WWW / No-WWW

Dovresti davvero fare l’uno o l’altro. Per coerenza, oltre che per SEO, amor.

 

Forza il www.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^your-site.com [NC]
RewriteRule ^(.*)$ http://www.your-site.com/$1 [L,R=301]

Rimuovi il www.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^your-site.com$ [NC]
RewriteRule ^(.*)$ http://your-site.com/$1 [L,R=301]

 

Spero che questi snippets per il file htaccess siano di votro aiuto e possano rendere il vostro sito un po’ piu sicuro.

 

1 commento su “htaccess file codici utili”

  1. Pingback: Modificare i Permalink in wordpress e redirect dei vecchi url *

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *