Bien gérer un htaccess pour url rewriting ou login,blocage d’ip

Bien gérer un htaccess pour url rewriting ou login,blocage d’ip

Quentin C. 20 February 2011

Bon, j’ai pu observer que bon nombre d’entre nous utilise l’htaccess sans pour autant le comprendre.

Ou l’utilise mal et on ne comprend pas pourquoi cela ne marche pas…

Je vais donc vous lister une partie non exhaustive des commandes que l’on peut utiliser avec des commentaires.

Je vous invite à les copier dans Notepad++ et à essayer de les comprendre (un copié-coller ne servira à rien , des commandes s’annulent ou ne sont pas complètes -> chemin absolu de fichier)
#Permet de désactiver les variables global (comme un ini_set en PHP)
SetEnv REGISTER_GLOBALS 0

#Désactiver le listage de dossier sans index.php
Options -Indexes

#Désactivation des Etag
FileETag none

#On active l'URL rewitting (ne sert à rien à mettre plusieurs fois)
RewriteEngine on

#On spécifie depuis quel dossier il prend effet (par exemple /forums est possible)
RewriteBase /

#Si on surfe sur index.html cela redirige sur index.php ou test.html -> test.php
RewriteRule ^(.*)\.html$ $1.php [L]

#Bloquage de le partie administration pour forum PUNBB/FLUXBB
<FilesMatch "^(admin_bans|admin_categories|admin_censoring|admin_common|admin_ext|admin_forums|admin_groups|admin_index|admin_prune|admin_ranks|admin_reindex|admin_reports|admin_settings|admin_users)\.php$">
AuthName "Who is it ?"
AuthType Basic
AuthUserFile /home7/.../.htpasswd  -->Spéficifier le chemin du .htpasswd
Require valid-user
</FilesMatch>

#Bloque seulement l'ip 8.8.8.8
<limit GET>
Order Allow,Deny
allow from all
deny from 8.8.8.8
</limit>

#Accepte seulement l'ip 8.8.8.8
<limit GET>
Order Deny,Allow
Deny from all
Allow from 8.8.8.8
</limit>

###FILTRE CONTRE ROBOTS DES PIRATES ET ASPIRATEURS DE SITE WEB
## EXCEPTION: TOUS LES ROBOTS MÊMES ANONYMES OU BANNIS PEUVENT ACCÉDER A CES FICHIERS
RewriteCond %{REQUEST_URI} !^/robots.txt
RewriteCond %{REQUEST_URI} !^/sitemap.xml

#REDICTION SS WWW to WWW
RewriteCond %{HTTP_HOST} ^avis-planethoster.com
RewriteRule (.*) [R=301,L]

# Change le tempis de mise en cache du browser 1 YEAR
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
Header set Cache-Control "max-age=29030400, public"
</FilesMatch>
# 8 WEEK
<FilesMatch "\.(jpg|jpeg|png|gif|swf|js)$">
Header set Cache-Control "max-age=4838400, public"
</FilesMatch>
# 3 HOUR
<FilesMatch "\.(oscthumb.php|txt|xml|css)$">
Header set Cache-Control "max-age=10800"
</FilesMatch>
# NEVER CACHE
<FilesMatch "\.(html|htm|php|cgi|pl)$">
Header set Cache-Control "max-age=0, private, no-store, no-cache, must-revalidate"
</FilesMatch>

#Si le module expires est présent
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType image/jpg "access plus 30 days"
ExpiresByType image/gif "access plus 30 days"
ExpiresByType image/jpeg "access plus 30 days"
ExpiresByType image/png "access plus 30 days"
ExpiresByType text/javascript "access plus 30 days"
ExpiresByType application/x-javascript "access plus 30 days"
ExpiresByType text/css "access plus 30 days"
ExpiresDefault "access plus 1 seconds"
</IfModule>

### SEUL LE FICHIER index.php EST SERVI COMME PREMIER FICHIER PAR DÉFAUT. LES AUTRES SONT INTERDITS
DirectoryIndex index.php

### INTERDIRE LES AUTRES TYPES DE FICHIER INDEX
<Files ~ "^(index)\.(p?s?x?htm?|txt|aspx?|cfml?|cgi|pl|php[3-9]|jsp|xml)$">
order allow,deny
deny from all
</Files>

### INTERDIRE L'AFFICHAGE DE CERTAINS FORMATS DE FICHIER
### EXÉCUTÉS PAR LE SERVEUR MAIS INTERDIT D'AFFICHAGE PAR LE NAVIGATEUR WEB
<Files ~ "\.(inc|class|sql|ini|conf|exe|dll|bin|tpl|bkp|dat|c|h|py|spd|theme|module)$">
deny from all
</Files>

### INTERDIRE L'AFFICHAGE DE CERTAINS FICHIERS COMME config, option, login, setup, install, admin.
### A ADAPTER SI CELA POSE PROBLÈME
<Files ~ "^((wp-)?config(\.inc)?|configure|configuration|options?\.inc|option|settings?(\.inc)?|functions?(\.inc)?|setup(\.inc)?|default|home|main|install?|admin|errors?|hacke?r?d?|[-_a-z0-9.]*mafia[-_a-z0-9.]*|[-_a-z0-9.]*power[-_a-z0-9.]*|[-_a-z0-9.]*jihad[-_a-z0-9.]*|php|shell|ssh|root|cmd|[0-9]{1,6}|test|data)\.(p?s?x?htm?l?|txt|aspx?|cfml?|cgi|pl|php[3-9]{0,1}|jsp?|sql|xml)$">
order allow,deny
deny from all
</Files>

### ON ÉVITE LE VOL D'IMAGES, VIDÉO, SON, FEUILLE DE STYLE, PDF ET ZIP
### LES VISITEURS DOIVENT PASSER PAR LE SITE.
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://[-_a-z0-9.]*avis-planethoster\.com$ [NC]
RewriteCond %{HTTP_REFERER} !^http://[-_a-z0-9.]*avis-planethoster\.com/.*$ [NC]
RewriteRule .*\.(gif|jpe?g?|jp2|png|svgz?|ico|css|pdf|zip|gz|js|mp3|m4a|mp4|mov|divx|avi|wma?v?|wmp|swf|flv|docx?|xlsx?|pptx?|vbs|rtf|asf?x?|odt|ods|odp|odg|odb)$ - [NC,F]

### DES FAUX URLS, ON LES NEUTRALISE
RedirectMatch gone ^/_vti.*
RedirectMatch gone ^/MSOffice.*
RedirectMatch gone ^[-_a-z0-9/\.]*//.*
RedirectMatch gone ^.*/etc/passwd.*

### FILTRE CONTRE XSS, REDIRECTIONS HTTP, base64_encode, VARIABLE PHP GLOBALS VIA URL, MODIFIER VARIABLE _REQUEST VIA URL, TEST DE FAILLE PHP, INJECTION SQL SIMPLE
RewriteEngine On
RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]
RewriteCond %{QUERY_STRING} ^(.*)(%3C|<)/?script(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=)?javascript(%3A|:)(.*)$ [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)document\.location\.href(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)(%3D|=)http(%3A|:)(/|%2F){2}(.*)$ [NC,OR] ## ATTENTION A CETTE RÈGLE. ELLE PEUT CASSER CERTAINES REDIRECTIONS RESSEMBLANT A: http://www.truc.fr/index.php?r=http://www.google.fr ##
RewriteCond %{QUERY_STRING} ^(.*)base64_encode(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)GLOBALS(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)_REQUEST(=|[|%[0-9A-Z]{0,2})(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)(SELECT|INSERT|DELETE|CHAR\(|UPDATE|REPLACE|LIMIT)(.*)$
RewriteRule (.*) - [F]

### FILTRE CONTRE PHPSHELL.PHP, REMOTEVIEW, c99Shell et autres
RewriteEngine On
RewriteCond %{REQUEST_URI} .*((php|my)?shell|remview.*|phpremoteview.*|sshphp.*|pcom|nstview.*|c99|r57|webadmin.*|phpget.*|phpwriter.*|fileditor.*|locus7.*|storm7.*)\.(p?s?x?htm?l?|txt|aspx?|cfml?|cgi|pl|php[3-9]{0,1}|jsp?|sql|xml) [NC,OR]
RewriteCond %{REQUEST_METHOD} (GET|POST) [NC]
RewriteCond %{QUERY_STRING} ^(.*)=/home(.+)?/loginftp/(.*)$ [OR]
RewriteCond %{QUERY_STRING} ^work_dir=.*$ [OR]
RewriteCond %{QUERY_STRING} ^command=.*&output.*$ [OR]
RewriteCond %{QUERY_STRING} ^nts_[a-z0-9_]{0,10}=.*$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)cmd=.*$ [OR] ## ATTENTION A CETTE REGLE. ELLE PEUT CASSER VOTRE SITE ##
RewriteCond %{QUERY_STRING} ^c=(t|setup|codes)$ [OR]
RewriteCond %{QUERY_STRING} ^act=((about|cmd|selfremove|chbd|trojan|backc|massbrowsersploit|exploits|grablogins|upload.*)|((chmod|f)&f=.*))$ [OR]
RewriteCond %{QUERY_STRING} ^act=(ls|search|fsbuff|encoder|tools|processes|ftpquickbrute|security|sql|eval|update|feedback|cmd|gofile|mkfile)&d=.*$ [OR]
RewriteCond %{QUERY_STRING} ^&?c=(l?v?i?&d=|v&fnot=|setup&ref=|l&r=|d&d=|tree&d|t&d=|e&d=|i&d=|codes|md5crack).*$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)([-_a-z]{1,15})=(ls|cd|cat|rm|mv|vim|chmod|chdir|mkdir|rmdir|pwd|clear|whoami|uname|tar|zip|unzip|tar|gzip|gunzip|grep|more|ln|umask|telnet|ssh|ftp|head|tail|which|mkmode|touch|logname|edit_file|search_text|find_text|php_eval|download_file|ftp_file_down|ftp_file_up|ftp_brute|mail_file|mysql|mysql_dump|db_query)([^a-zA-Z0-9].+)*$ [OR]
RewriteCond %{QUERY_STRING} ^(.*)(wget|shell_exec|passthru|system|exec|popen|proc_open)(.*)$
RewriteRule (.*) - [F]

## EXCEPTION: SI UTILISATION DE *PAYPAL INSTANT NOTIFICATION PAYMENT*, COMME PAYPAL N'UTILISE PAS DE HTTP_USER_AGENT, L'IPN NE MARCHERA PAS.
RewriteCond %{REQUEST_URI} !^/paypal-ipn.php
RewriteCond %{HTTP_USER_AGENT} ^-?$ [OR] ## ANONYMES
RewriteCond %{HTTP_USER_AGENT} ^[bcdfghjklmnpqrstvwxz\ ]{8,}|^[0-9a-z]{15,}|^[0-9A-Za-z]{19,}|^[A-Za-z]{3,}\ [a-z]{4,}\ [a-z]{4,} [OR] ## CEUX QUI INVENTENT DES NOMS AU HASARD
RewriteCond %{HTTP_USER_AGENT} ^<sc|<\?|8484\ Boston\ Project|autoemailspider|@nonymouse|ADSARobot|Advanced\ Email\ Extractor|^adwords|ah-ha|aktuelles|amzn_assoc|Anarchie|anonymous|Art-Online|ASPSeek|ASSORT|ATHENS|Atomz|attach|autoemailspider|BackWeb|Bandit|BatchFTP|bdfetch|big.brother|BlackWidow|blogsearchbot-martin|bmclient|Boston\ Project|BravoBrian\ SpiderEngine\ MarcoPolo|Bullseye|bumblebee|capture|CherryPicker|ChinaClaw|CICC|clipping|compatible\ \;|Crescent|Crescent\ Internet|Custo|cyberalert|Deweb|diagem|Digger|Digimarc|DIIbot|DirectUpdate|disco|DISCoFinder|Downloader|Download\ Accelerator|Download\ Demon|Download\ Wonder|Drip|DSurf15a|DTS.Agent|EasyDL|eCatch|echo\ extense|ecollector|efp@gmx\.net|EirGrabber|EmailCollector|EmailSiphon|Email\ Siphon|EmailWolf|Email\ Extractor|Express\ WebPictures|ExtractorPro [NC,OR] ## VRAIS ET FAUX ROBOTS NE RESPECTANT PAS LES REGLES
RewriteCond %{HTTP_USER_AGENT} EyeNetIE|fastlwspider|FavOrg|Favorites\ Sweeper|^Fetch|FEZhead|FileHound|flashget|FlashGet\ WebWasher|FlickBot|fluffy|frontpage|GalaxyBot|Generic|Getleft|GetRight|GetSmart|GetWeb!|GetWebPage|gigabaz|Girafabot|Go!Zilla|go-ahead-got-it|GornKer|Grabber|GrabNet|Grafula|Green\ Research|grub-client|grub\ crawler|hanzoweb|Harvest|hhjhj@yahoo|hloader|HMView|HomePageSearch|HTTPConnect|httpdown|httplib|HttpProxy|HTTP\ agent|http\ generic|HTTrack|ia_archive|IBM_Planetwide|IDBot|id-search|imagefetch|Image\ Stripper|Image\ Sucker|IncyWincy|Indy\ Library|informant|Ingelin|InterGET|InternetLinkAgent|InternetSeer\.com|^Internet\ Explorer|Internet\ Ninja|IPiumBot|Iria|Irvine|Jakarta\ Commons|JBH*Agent [NC,OR] ## VRAIS ET FAUX ROBOTS NE RESPECTANT PAS LES REGLES
RewriteCond %{HTTP_USER_AGENT} JetCar|JOC|JOC\ Web\ Spider|JustView|Kapere|KWebGet|Lachesis|larbin|LeechFTP|LexiBot|lftp|likse|Link*Sleuth|LINKS\ ARoMATIZED|LinkWalker|Mac\ Finder|Mag-Net|Magnet|Mass\ Downloader|MCspider|Microsoft\ URL|Microsoft\ Data|MIDown\ tool|minibot\(NaverRobot\)|Mirror|Missigua|Mister\ PiX|MJ12bot|MMMtoCrawl\/UrlDispatcherLLL|Movable\ Type|Moozilla|^Mozilla$|^MSIE|Murzillo|MSProxy|multithreaddb|nationaldirectory|Navroad|NearSite|NetAnts|NetCarta|NetMechanic|netprospector|NetResearchServer|NetSpider|NetZIP|NetZippy|NetZip\ Downloader|Net\ Vampire|NEWT|nicerspro|NICErsPRO|NPBot|Nutch|Nutscrape/|Octopus|Offline\ Explorer|Offline\ Navigator|OmniExplorer|OpaL|Openfind|OpenTextSiteCrawler [NC,OR] ## VRAIS ET FAUX ROBOTS NE RESPECTANT PAS LES REGLES
RewriteCond %{HTTP_USER_AGENT} OrangeBot|PackRat|PageGrabber|Papa\ Foto|pavuk|pcBrowser|PersonaPilot|PingALink|Pockey|Program\ Shareware|Proxy|psbot|PSurf|psycheclone|^puf|Pump|PushSite|PussyCat|PycURL|python|QRVA|QuepasaCreep|RealDownload|Reaper|Recorder|ReGet|replacer|RepoMonkey|almaden|Robozilla|Rover|RPT-HTTPClient|Rsync|SearchExpress|searchhippo|searchterms\.it|Second\ Street\ Research|Seeker|Shai|sitecheck|SiteMapper|SiteSnagger|SlySearch|SmartDownload|snagger|SpaceBison|Spegla|SpiderBot|SqWorm|Star\ Downloader|Stripper|sucker|SuperBot|SuperHTTP|Surfbot|SurfWalker|SurveyBot|Szukacz|tAkeOut|tarspider|Teleport\ Pro|Telesoft|Templeton|TrackBack|TrueRobot|Turing|TurnitinBot [NC,OR] ## VRAIS ET FAUX ROBOTS NE RESPECTANT PAS LES REGLES
RewriteCond %{HTTP_USER_AGENT} TV33_Mercator|UIowaCrawler|URL_Spider_Pro|^user|^User\ Agent:\ |^User-Agent:\ |UtilMind|Vacuum|vagabondo|vayala|visibilitygap|vobsub|VoidEYE|vspider|w3mir|WebaltBot|WebAuto|webbandit|WebCapture|Webclipping|webcollage|webcollector|WebCopier|webcraft@bea|WebDAV|webdevil|webdownloader|Webdup|WebEmailExtractor|WebFetch|WebGo\ IS|WebHook|Webinator|WebLeacher|WEBMASTERS|WebMiner|WebMirror|webmole|WebReaper|WebSauger|WEBsaver|Website\ eXtractor|Website\ Quester|WebSnake|Webster|WebStripper|websucker|webvac|webwalk|webweasel|WebWhacker|WebZIP|Web\ Data\ Extractor|Web\ Downloader|Web\ Image\ Collector|Web\ Sucker|web\.by\.mail|whizbang|WhosTalking|Widow|Widows|WISEbot|WISEnutbot|WUMPUS|Wweb|WWWOFFLE|Wysigot|x-Tractor|Xaldon\ WebSpider|XGET|Yandex|Zeus|Zeus.*Webster [NC] ## VRAIS ET FAUX ROBOTS NE RESPECTANT PAS LES REGLES
RewriteCond %{HTTP_USER_AGENT} ^curl|^Fetch\ API\ Request|GT\:\:WWW|^HTTP\:\:Lite|httplib|^Java/1.|^Java\ 1.|^LWP|libWeb|libwww|^PEAR|PECL\:\:HTTP|PHPCrawl|^Program\ Shareware|python|Rsync|Snoopy|^URI\:\:Fetch|WebDAV|^Wget [NC] ## BIBLIOTHEQUES / CLASSES HTTP DONT ON NE VEUT PAS. ATTENTION, CELA PEUT BLOQUER CERTAINES FONCTIONS DE VOTRE CMS. NE PAS TOUT EFFACER, MAIS CHERCHEZ LE NOM DE LA CLASSE HTTP CONCERNEE (DEMANDEZ AUX DEVELOPPEURS DE VOTRE CMS). CETTE LISTE BLOQUE 80% DES ROBOTS SPAMMEURS. IL FAUT LA CONSERVER.
RewriteRule (.*) - [F]

9 thoughts on “Bien gérer un htaccess pour url rewriting ou login,blocage d’ip

  1. Bonjour,
    J’ai été victime d’un piratage hors du commun.
    J’ai résolu le problème.

    il se trouve que tous mes fichiers .htaccess ont été piratés. Il y a eu des modifications à l’intérieur. Redirections vers un site de malware, dixit google. beaucoup d’espaces à l’intérieur pour ne pas voir à l’écran les redirections (colonne 350 et suivantes)
    Il renvoyait vers un site nommé googlesgo.c o m
    Vous pouvez voir une copie d’écran du fichier .htaccess vérolé (retravaillé pour passer à l’écran) sur mon blog :
    https://blog.avis-planethoster.com
    Meme dans les répertoires _cnf, _log, _private etc…. les fichiers htaccess ont été vérolés.
    Comment est ce possible ?

    NB: la modif aurait eu lieu le 07/03/2012 vers 21h18 heure francaise.

    Comment est il possible de modifier ces fichiers .HTACCESS sans les mots de passe ?
    Et surtout dans des dossiers non visibles par le public ?

    Merci de vos lumières

  2. Bonjour,

    Peut-on espérer améliorer la sécurité de son site avec les parties :

    – ### INTERDIRE L’AFFICHAGE DE CERTAINS FICHIERS

    – ### ON ÉVITE LE VOL D’IMAGES, VIDÉO, SON, FEUILLE DE STYLE, PDF ET ZIP
    ### LES VISITEURS DOIVENT PASSER PAR LE SITE.

    – ### DES FAUX URLS, ON LES NEUTRALISE

    – ### FILTRE CONTRE XSS, REDIRECTIONS HTTP, base64_encode, VARIABLE PHP GLOBALS VIA URL, MODIFIER VARIABLE _REQUEST VIA URL, TEST DE FAILLE PHP, INJECTION SQL SIMPLE

    Il suffirait de les rajouter dans le htaccess actuel pour cela?

    Pourquoi la dernière partie sur paypal est-elle aussi grande?

    Je m’excuse par avance mais le fichier htaccess est trés obscure pour moi :-/

  3. – ### INTERDIRE L’AFFICHAGE DE CERTAINS FICHIERS

    Lorsque votre site est en production, vous devez limiter l’accèss a des fichiers d’installations/dumps SQL/fichier de log/…
    Il ne faut pas donner accès les fichiers sensibles qui peuvent rester sur l’hébergement !

    – ### ON ÉVITE LE VOL D’IMAGES, VIDÉO, SON, FEUILLE DE STYLE, PDF ET ZIP
    ### LES VISITEURS DOIVENT PASSER PAR LE SITE.

    Par exemple vous avez une galerie d’image situé dans un dossier (https://blog.avis-planethoster.com/wp-content/uploads/ par exemple)
    Vous avez un petit hébergement avec une bande passante assez restrictive et un concurent utilise vos images qui sont stocké sur votre serveur …(PAS COOL!)
    Avec ce code qui la balise n’est pas sur votre site, l’image ne s’affichera pas 😉

    – ### DES FAUX URLS, ON LES NEUTRALISE

    Par défault les hebergeur laisse un squelette de site web avec des pages préformaté (on connait tous le ‘It’s works’ d’Apache)
    Bien évidemment on ne laisse pas accès pour ne pas avoir de contenu dupliqué!
    Ici : vti=FrontPage , MSOffice=Microsoft Office , ….

    – ### FILTRE CONTRE XSS, REDIRECTIONS HTTP, base64_encode, VARIABLE PHP GLOBALS VIA URL, MODIFIER VARIABLE _REQUEST VIA URL, TEST DE FAILLE PHP, INJECTION SQL SIMPLE

    On ne veut pas qu’un Hackeur attaque les scripts PHP avec des variables contenant du code java/script ou de code SQL !

  4. Bonjour,
    C’ est un gros travail le htaccess.

    Pour ma part j’ai un petit souci loin de toute ces utilisation:
    Le htaccess avec passage d’argument ne fonctionne que si je met un – devant et je n’ arrive pas a detecter comment y remédier.
    Si vous aviez un petit conseil a me donner pour enlever ce -.

    Options +FollowSymlinks
    RewriteEngine On
    #///fonctionne
    RewriteRule ^-([a-zA-Z0-9-]+).php$ /TestEtEssais/acceuil.php?alias=$1 [L]

    merci

  5. Merci pour ce billet, j’ai considérablement amélioré la sécurité de mon site web avec ça.

    Toutefois, j’aimerais connaitre les classes HTTP qui peuvent empêcher le bon fonctionnement de Joomla 1.5.

  6. Bjour,

    dans la partie ### FILTRE CONTRE XSS, REDIRECTIONS HTTP, base64_encode, VARIABLE PHP GLOBALS VIA URL, MODIFIER VARIABLE _REQUEST VIA URL, TEST DE FAILLE PHP, INJECTION SQL SIMPLE

    ne serait t’il pas plus judicieux dans les dernières lignes de mettre [NC, OR] et pas simplement [OR] qui enlève pas mal d’efficacité à la chose ?

Leave a Reply to jaymee126 Cancel reply

Your email address will not be published.